Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to increment counter in Jinja2

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.

like image 579
ryu.h Avatar asked Oct 16 '25 01:10

ryu.h


1 Answers

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

like image 153
β.εηοιτ.βε Avatar answered Oct 19 '25 14:10

β.εηοιτ.βε



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!