Django模板中reversed与slice结合后forloop.counter0不符合预期
Django模板中slice和reversed未按预期生成索引的解决方法
问题根源
你混淆了列表元素值和元素的原索引:
slice:"6:12"是取出game.board中索引6到11的元素(共6个),而非索引本身。reversed仅反转这些元素的遍历顺序,但如果这些元素的值是0-5,反转后只会得到5-0,不是你需要的原索引11-6。
解决方案
方法一:视图层生成目标索引列表(推荐)
在视图函数中直接生成需要的索引范围,传给模板:
# 生成从11到6的整数列表(步长-1) pit_indices = list(range(11, 5, -1)) # 将索引列表加入模板上下文 context = { 'game': game, 'pit_indices': pit_indices } return render(request, 'your_template.html', context)
模板中直接遍历这个索引列表:
{% for pit in pit_indices %} <!-- 这里的pit就是11、10、9...6,直接传给make_move视图即可 --> <button onclick="location.href='{% url 'make_move' pit %}'">{{ pit }}</button> {% endfor %}
方法二:模板内计算原索引(不推荐,可读性差)
如果必须在模板中处理,可通过forloop.counter0(从0开始的循环计数器)计算原索引:
{% for item in game.board|slice:"6:12" reversed %} {% with pit=11|add:forloop.counter0|mul:-1|add:11 %} <!-- 计算逻辑:原索引 = 11 - 循环计数器(0到5) --> <button onclick="location.href='{% url 'make_move' pit %}'">{{ pit }}</button> {% endwith %} {% endfor %}
内容的提问来源于stack exchange,提问作者trexgris
相关产品推荐
相关产品推荐

