IsaTTeN
(Sebastian)
May 24, 2020, 7:22pm
1
Hello!
I´m trying to build a sensor using templates but I´m stucked because the set instruction isn´t working inside a for loop.
This is not the real sensor but reproduces the problem that I´m getting. In this example I never get the Hello World in the test variable. Why???
{% set number = 3 %}
{% for x in range(number | int) -%}
{{ x }}
{%- if x==2 %}
{% set test = 'Hello World!' %}
{% endif %}
{% endfor %}
{{ test }}
I get this in the Template Editor:
0
1
2
Thank you in advance
See “Scoping Behavior” under Assignments in the Jinja2 docs.
{% set number = 3 %}
{% set ns = namespace(test = '') %}
{% for x in range(number | int) -%}
{{ x }}
{%- if x==2 %}
{%- set ns.test = 'Hello World!' %}
{%- endif %}
{% endfor -%}
{{ ns.test }}
Results in:
0
1
2
Hello World!
IsaTTeN
(Sebastian)
May 24, 2020, 10:13pm
3
Thanks a lot @pnbruckner . I was stucked with this for 4 hours , ha ha
Thank you so much!!!
1 Like
123
(Taras)
May 24, 2020, 10:59pm
4
Post the real for-loop you have created. Depending on what you are trying to achieve, you may not need a for-loop.