Template variable warning: 'phrase' is undefined when rendering

The following code returns an error, I can’t do anything with that:


type: markdown
content: >-




  {% set ns = namespace(below=[]) %}
  {% set exclude = ['sensor.hue_smart_button_1_battery_level'] %}
  {% set threshold = 11 %}
  {% for s in states.sensor 
     if s.entity_id.endswith('battery_level') and s.state != 'unknown' and s.state |int < threshold and not s.entity_id in exclude %}
     {% set phrase = 'Batteriestand beachten:' %}
     {% set ns.below = ns.below + [ s.name[:-14] ~ ' (' ~ s.state ~ '%)'] %}
  {% endfor %}
  {{ phrase }} {{ ns.below | join(',') }}


  {% set b = states('sensor.xxxxxxxx_phone_battery_level')  %}
  {% if b |float(default=0) < 50  %}Bitte iPhone laden ({{ b }}%)
  {% else %}
  {% endif %}


Template variable warning: 'phrase' is undefined when rendering

Any explanation or link is much appreciated!

you’re running into scope issue. In jinja, you can’t access things created in a for loop unless you use namespace.

  {% set ns = namespace(below=[], phrase='') %}
...
  {% set ns.phrase = 'Batteriestand beachten:' %}
...
  {{ ns.phrase }} {{ ns.below | join(',') }}

Would never have thought of it myself. Thank you very much!