[Tera] Variable assignment in `for` loop

Hello!

{% set var = 1.7 %}
{% set array = [15, "true", 1.7, 33, 26,] %}

{% for i in array %}
  {{ i ~ " " ~ var -}}
  {% set var = 2 -%}
{% endfor %}

O/p:

  15 1.7
  true 1.7
  1.7 1.7
  33 1.7
  26 1.7

I expected except first all remaining 4 lines to have 2 at the end. It looks like it didn’t pick up setting value 2. Why is so?

Thanks!

Interestingly, if I put the set statement before printing var then I get 2 at the end of all 5 lines as expected.

For loops create another stack frame where the value set is local to that loop, that’s a classic gotcha of Jinja2.
If you want to update a value outside of the for loop, you need to use set_global

But I’m not updating the value outside the loop nor am I printing the value outside the loop.

I have {% set var = 2 -%} inside the for loop after print statement (please check source code posted above). I am curious to know why the print statement in for loop is not picking up that set statement (which itself is inside the loop).

As pointed out in subsequent comment, the value does get picked up if the order of those 2 statements are reversed. What difference does it make? Both statements are still inside the loop.

{% set var = 1.7 %}
{% set array = [15, "true", 1.7, 33, 26,] %}

{% for i in array %}
  {{ i ~ " " ~ var -}}   <-- this looks for a `var` in the loop, doesn't find it and then looks up in the global context
  {% set var = 2 -%} <-- this sets a variable in the current iteration (NOT the whole for loop). Since there is nothing after, this is essentially a no-op as this context gets cleared for the next loop
{% endfor %}

If you invert it, then the concatenation will find the var value of the iteration (2) since it’s set rather than 1.7

1 Like

Thank you!

Tera docs doesn’t say anything about assignments in for loop getting cleared at the end of the iteration.

We should have a text like Jinja:

Please note that assignments in loops will be cleared at the end of the iteration

I’m adding this in Improvements to docs by rootkea · Pull Request #635 · Keats/tera · GitHub