How to increment a variable on a for loop in jinja template?

user422100 picture user422100 · Sep 24, 2011 · Viewed 117.8k times · Source

I would like to do something like:

variable p is from test.py which is a list ['a','b','c','d']

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

result output is:
1 2 3 4

Answer

zeekay picture zeekay · Sep 24, 2011

You could use loop.index:

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

Check the template designer documentation.

In more recent versions, due to scoping rules, the following would not work:

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