Counting simple variable in jinja (loop)

It doesn’t work the way you expect because of the variable’s scope which is constrained to an iteration (loop) of the for loop. In other words, changes made to the variable are not carried over from one iteration to another; each iteration starts with the original value, 0, of the variable c.

To do what you want, you have to use namespace to define a variable whose scope extends across all iterations.

        {% set ns = namespace(c = 0) %}
        {% for i in range(0,10) %}
          {% set ns.c = ns.c + 2 %}
          {{  ns.c  }}
        {% endfor %}

2 Likes