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

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


Solution 1:

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 %}

Solution 2:

After 2.10, to solve the scope problem, you can do something like this:

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

Solution 3:

As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.

You can defeat this behavior by using an object rather than a scalar for 'count':

{% set count = [1] %}

You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):

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

Or...

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

(From comments by @eyettea and @PYB)