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

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


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


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


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)