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.
This happens because of the scoping behaviour of blocks in Jinja:
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 correspondingendfor
.But, as explained later in the same note of the documentation, you can work around this using a namespace.
Which yields the expected