Updating the value of a template variable inside a loop

I’m trying to write a helper that returns true if any of the TrueNAS Cloud Sync jobs are running. I’ve debugged this code and the innermost conditional for state == "RUNNING" is evaluating to true, but the value of running is not getting updated and always returns “Off”. Is there a better way to properly return “On” for this binary sensor if the innermost condition is true, or am I just missing something obvious? I’m not much of a Jinja ninja.

{% set running = "Off" %}
{% for state in states.sensor %}
  {% if "bb_" in state.entity_id %}
    {% if (is_state(state.entity_id, 'RUNNING')) %}
      {% set running = "On" %}
      {% break %}
    {% endif %}
  {% endif %}
{% endfor %}
{{ running }}

In the for-loop you need to use namespace…try this

{% set ns = namespace(running = "Off") %}
{% for state in states.sensor %}
  {% if "bb_" in state.entity_id %}
    {% if (is_state(state.entity_id, 'RUNNING')) %}
      {% set ns.running = "On" %}
      {% break %}
    {% endif %}
  {% endif %}
{% endfor %}
{{ ns.running }}
2 Likes

If you’re interested, you can achieve your goal without employing a for-loop.

{{ states.sensor 
  | selectattr('object_id', 'search', 'bb_')
  | selectattr('state', 'eq', 'RUNNING')
  | list | count > 0 }}

The template reporys true if there’s at least one sensor whose state is RUNNING. Otherwise it reports false. The values true and false are reported as on and off by a Template Binary Sensor.

3 Likes

I would love to be in your brain (not too much I guess) just to see how you derive to … this can be much simpler :crazy_face:

Ok that is a sexy solution. Thank you!

2 Likes