For i in range loop

hi, i am trying to repeat a calculation using a ‘for i in range’ loop and then use the result of the calculation; however, the variable i use inside the loop appears to not be defined outside the loop; example:

{% set x=0 %}
{% for i in range(1,10) %}
  {% x = x + i %}
{% endfor %}
{{ x }}

anyone knows what is wrong here?

You need to use namespace variables to be able to do that.
I’m currently typing on my phone so I can’t create a good example now (and I don’t remember the syntax either).
But search for namespace and I’m sure you will find lots of examples.

As @Hellis81 said, use jinja2 namespace.

{% set ns = namespace(x=0) %} 
{% for i in range(1,10) %}
  {% set ns.x = ns.x + i %}
{% endfor %}
{{ ns.x }}
1 Like

thanks, perfect!

thanks, will do