How to simplify this binary_sensor template, using filters with count or loops?

A Jinja2 variable defined outside of a for loop can be assigned a different value inside the for loop but that value only exists inside the for loop. Outside of the for loop, the variable’s value remains unchanged by whatever may have been done inside the for loop.

Obviously this presents a problem when you want the for loop to modify the variable’s value. That’s where namespace is useful. It allows you to define a Jinja2 variable that can be assigned a value inside a for loop that is retained outside of the for loop.

You can test it for yourself:

{% set x = 0 %}
{% set ns = namespace(y=0) %}

{%- for i in range(0, 5) %}
  {% set x = x + 1 %}
  {% set ns.y = ns.y + 1 %}
{% endfor -%}
x: {{ x }}
y: {{ ns.y }}

3 Likes