如何在jinja模板的for循环中递增变量?

123 投票
8 回答
205930 浏览
提问于 2025-04-17 02:59

我想做一些类似的事情:

变量 p 来自 test.py,它是一个列表,内容是 ['a','b','c','d']

{% for i in p %}
{{variable++}}
{{variable}}

结果输出是:
1 2 3 4

8 个回答

66

正如Jeroen所说,这里有作用域的问题:如果你在循环外面设置了'count',那么在循环里面就不能修改它。

你可以通过使用一个对象来代替标量(简单的数值)来解决这个问题,这样就可以修改'count'了:

{% set count = [1] %}

现在你可以在for循环里面或者甚至在%include%里面操作count。下面是我如何增加count的(是的,这个方法有点笨,但没办法):

{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}

或者...

{% set count = [] %}
{% for something-that-loops %}
   {% set __ = count.append(1) %} 
   <div> Lorem ipsum meepzip dolor...
   {{ count|length }}
   </div>
{% endfor %}

(来自@eyettea和@PYB的评论)

126

在2.10版本之后,为了解决作用域的问题,你可以这样做:

{% set count = namespace(value=0) %}
{% for i in p %}
  {{ count.value }}
  {% set count.value = count.value + 1 %}
{% endfor %}
205

你可以使用 loop.index

{% for i in p %}
  {{ loop.index }}
{% endfor %}

查看 模板设计文档

在更新的版本中,由于作用域规则,下面的代码将 无法 工作:

{% set count = 1 %}
{% for i in p %}
  {{ count }}
  {% set count = count + 1 %}
{% endfor %}

撰写回答