Hi all
I’m new to programming in HA. I’m playing around in Template Tools and cannot get something to append to a string. Can someone please assist?
{% set val = "" %}
{% set ns = namespace(c = 0) %}
{% for i in ['1','2','3'] %}
{% set val = val|string + "5" %}
{{ val }}
{% set ns.c = ns.c + 1 %}
{% endfor %}
val = {{ val }}
If you just remove the last line then the result in a template sensor should be 555.
In the template tools it looks differently, but all spaces are removed in a sensor.
{% set val = "" %}
{% set ns = namespace(c = 0) %}
{% for i in ['1','2','3'] -%}
{{ 'val = ' if loop.first -}}
{% set val = val|string + "5" -%}
{{ val -}}
{% set ns.c = ns.c + 1 -%}
{% endfor %}
In Jinja2, the scope of a variable defined within a for-loop is limited to the for-loop. A variable defined outside a for-loop can be modified within a for-loop but that value isn’t preserved outside of the for-loop. To get the variable’s scope to cover inside and outside the for-loop, use namespace.
{% set ns = namespace(c = '') %}
{% for i in range(0,3) %}
{% set ns.c = ns.c ~ '5' %}
{% endfor %}
{{ ns.c }}
In addition, is you use the + operator it will naturally attempt to compute the sum of numbers. If you want to append numeric strings, and eliminate any ambiguity of whether the values should be summed or concatenated, use the ~ operator.