Trying to increment counter in Jinja2

273 Views Asked by At

I am trying to increment a counter variable to print the numbers one to six

{% set counter = 1 %}

{% for i in range(3) %}
    {% for j in range(2) %}
        {{ counter }}
        {% set counter = counter + 1 %}
    {% endfor %}
{% endfor %}

However, the counter variable is stuck at one, and my output is:




····
········1
········
····
········1
········
····

····
········1
········
····
········1
········
····

····
········1
········
····
········1
········
····

Note: I am using an online Jinja2 live parser http://jinja.quantprogramming.com/ to help run this code.

1

There are 1 best solutions below

0
On

This happens because of the scoping behaviour of blocks in Jinja:

Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope.

Source: https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments, emphasis, mine.

So, in your case, that means that the incrementation you are doing inside the block created by the loop for j in range(2) is not visible outside of that block — after its corresponding endfor.

But, as explained later in the same note of the documentation, you can work around this using a namespace.

{% set ns = namespace(counter=1) %}

{% for i in range(3) %}
    {% for j in range(2) %}
        {{ ns.counter }}
        {% set ns.counter = ns.counter + 1 %}
    {% endfor %}
{% endfor %}

Which yields the expected




····
········1
········
····
········2
········
····

····
········3
········
····
········4
········
····

····
········5
········
····
········6
········
····