Python Django forloop索引操作
我很难理解Django的forloop.counter是什么。我的意图是将for循环的每三次迭代封装在Python Django forloop索引操作,python,django,for-loop,django-templates,Python,Django,For Loop,Django Templates,我很难理解Django的forloop.counter是什么。我的意图是将for循环的每三次迭代封装在中。我期望它如何工作是这样的: {% for staff in staff_members %} {% if (forloop.counter + 2 % 3) == 0 %} // if loop is the first of three <div class="row"> {% endif %} {{ staff }} // c
中。我期望它如何工作是这样的:
{% 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 %}
{%用于staff_members%}
{%if(forloop.counter+2%3)=0%}//if循环是三个循环中的第一个
{%endif%}
{{staff}}
//如果循环是三个循环中的最后一个,则关闭
{%endfor%}
这不起作用,因为Django似乎不喜欢在forloop.counter上操作。在视图中执行此操作似乎过于复杂,我更愿意在模板中执行,因为这纯粹是一个表示/样式问题。您可以使用
例如:
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]}))
从django.template导入模板,上下文
t=模板(“”)
{staff_members%}中的职员为%
{%cycle'''作为div%}
{{staff}}
{%cycle'''作为div%}
{%endfor%}
{如果不是工作人员|长度|可除比例:3%}
{%endif%}
""")
print t t.render(上下文({'staff_members':[1,2,3,4,5,6,7,8]}))
打印(删除一些空行以便于阅读)
1.
2.
3.
4.
5.
6.
7.
8.
更新句柄结束标记。您需要将“”与内置项一起使用(如@falsetru所述)
对于您的具体要求,以下内容可以:
>>> t3 = Template("""
... {% for staff in staff_members %}
... {% cycle '<div class="row">' '' '' %}
... {{staff}}
... {%if forloop.counter|divisibleby:'3' %}
... </div>
... {%endif%}
... {%endfor%}
... """)
>>> print t3.render(Context({'staff_members': [1,2,3,4,5,6,7,8,9,10]}))
<div class="row">
1
2
3
</div>
<div class="row">
4
5
6
</div>
<div class="row">
7
8
9
</div>
<div class="row">
10
>>t3=模板(“”
…{staff_members%}
…{%周期'''''%}
…{{staff}
…{%if-forloop.counter | divisibleby:'3'}
...
…{%endif%}
…{%endfor%}
... """)
>>>打印t3.render(上下文({'staff_members':[1,2,3,4,5,6,7,8,9,10]}))
1.
2.
3.
4.
5.
6.
7.
8.
9
10
如果len(员工成员)%3!=0我希望这会有所帮助。forloop.counter给出了循环的当前迭代,并且是1索引的(即forloop.counter的第一次迭代值是1)这与“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 %}
{%用于staff_members%}
{%if-forloop.counter | divisibleby:3%}
{%endif%}
{{staff}}
{%if-forloop.counter0 | divisibleby:3%}
{%endfor%}
我明白了。我更熟悉细枝模板语言,它有时会模糊视图和模板之间的界限。感谢您的评论:)
{% for staff in staff_members %}
{% if forloop.counter|divisibleby:3 %}
<div class="row">
{% endif %}
{{ staff }}
{% if forloop.counter0|divisibleby:3 %}
</div>
{% endfor %}