1

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.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
ryu.h
  • 11
  • 1
  • Does this answer your question? [Jinja2: Change the value of a variable inside a loop](https://stackoverflow.com/questions/9486393/jinja2-change-the-value-of-a-variable-inside-a-loop) – β.εηοιτ.βε Jun 02 '23 at 07:05

1 Answers1

0

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
········
····

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83