我很难理解 Django 的 forloop.counter 是什么。我的目的是将 for 循环的每三个迭代包装在 <div>
中。我期望它如何工作是这样的:
{% for staff in staff_members %}
{% if (forloop.counter + 2 % 3) == 0 %} // if loop is the first of three
<div class="row">
{% endif %}
{{ staff }}
// close <div class="row"> if loop is last of three
{% endfor %}
这不起作用,因为 Django 似乎不喜欢在 forloop.counter 上进行操作。在 View 中执行此操作似乎过于复杂,我宁愿在模板中执行此操作,因为这纯粹是一个表示/样式问题。
最佳答案
这与“Django不喜欢在柜台上操作”无关。只是 Django 的模板语言在设计上不支持对任何变量进行此类操作。
正如其他人所指出的,有些标签可以满足您的需求。最简单的方法可能是使用 divisibleby
:
{% for staff in staff_members %}
{% if forloop.counter|divisibleby:3 %}
<div class="row">
{% endif %}
{{ staff }}
{% if forloop.counter0|divisibleby:3 %}
</div>
{% endfor %}
关于python - Django forloop索引操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698115/