我在Django中有2D forloop像这样:
{% for temp in data.lines.all %}
{% for item in temp.articles.all %}
<section class="{{ counter of these loops }}" >
{% include "page.html" %}
</section>
{% endfor %}
{% endfor %}
现在放置在{{这些循环的计数器}}中的内容将获得循环计数器的数量。
如果第一个循环有4个元素,每个元素有5个孩子,那么到最后我也必须有
counter = 20。
解决方案可以是从类似以下类的类创建计数器对象
class Counter:
counter = 0
def increment(self):
self.counter += 1
def set_to_zero(self):
self.counter = 0
并在上下文中传递它。然后你可以用
{{ counter.increment }}
但这很丑陋,因为如果您有很多循环,则必须在上下文中传递很多变量,并且在大多数情况下,更改模板中对象的状态不是一个好主意。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句