Counting simple variable in jinja (loop)

I am trying to create a simple loop where a variable is counted up. The variable is relevant for a later query.
Actually I would have the values 2, 4, 6… but I only get 2, 2, 2,…

Where is the error?

      value_template: >-
        {% set c = 0 %}
        {% for i in range(0,10) %}
          {% set c = c + 2 %}
          {{  c  }}
        {% endfor %}

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

Cool, thank you! I’ll try this :ok_hand: