我很难理解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上进行操作。在视图中执行此操作似乎过于复杂,我宁愿在模板中执行此操作,因为它纯粹是一个表示/样式问题。
您可以使用cycle
tag。
例如:
from django.template import Template, Context
t = Template("""
{% for staff in staff_members %}
{% cycle '<div class="row">' '' '' as div %}
{{ staff }}
{% cycle '' '' '</div>' as div %}
{% endfor %}
{% if not staff_members|length|divisibleby:3 %}
</div>
{% endif %}
""")
print t.render(Context({'staff_members': [1,2,3,4,5,6,7,8]}))
打印(删除一些空行以便于阅读)
<div class="row">
1
2
3
</div>
<div class="row">
4
5
6
</div>
<div class="row">
7
8
</div>
UPDATE处理结束标记。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句