Suppose you have the following code and you add a variable called cnt in the for statement.
count_test.j2
{%- set cnt = 1 -%}
{%- for i in range(3) -%}
{%- set cnt = cnt + 1 -%}
{{ cnt }}
{% endfor -%}
result : {{ cnt }}
Looking at the result, you can see that the result added to the variable is not inherited outside the for statement.
output
2
3
4
result : 1
Depending on the version, it seems that it may not be added.
output
2
2
2
result : 1
It works well if you store the added result in a list. Add the added value to the list with append, and delete the value before addition with pop.
count_test2.j2
{%- set cnt = [1] -%}
{%- for i in range(3) -%}
{%- set _ = cnt.append(cnt[0] + 1) -%}
{%- set _ = cnt.pop(0) -%}
{{ cnt[0] }}
{% endfor -%}
result : {{ cnt[0] }}
<2019/12/21: From na90ya> It seems that variables are preserved when using namespace objects introduced in 2.10 of jinja2. (Reference material [1])
count_test3.j2
{%- set ns = namespace(cnt=1) -%}
{%- for i in range(3) -%}
{%- set ns.cnt = ns.cnt + 1 -%}
{{ ns.cnt }}
{% endfor -%}
result : {{ ns.cnt }}
Looking at the result, the variables are still added outside the for statement.
output
2
3
4
result : 4
[[1]Template Designer Documentation] (https://jinja.palletsprojects.com/en/2.10.x/templates/#assignments)
Recommended Posts