#Can you post the jinja that you've tried
1 messages · Page 1 of 1 (latest)
{% set battery_sensors = states.sensor
| selectattr('entity_id', 'match', '.*_battery$')
| selectattr('state', '!=', 'unknown')
| selectattr('state', '!=', 'unavailable')
| list %}
{% if battery_sensors %}
{% set low_batteries = [] %}
{% for sensor in battery_sensors %}
{% if sensor.state | int < 25 %}
{% set low_batteries = low_batteries + [sensor] %}
{% endif %}
{% endfor %}
{% if low_batteries %}
<strong>Batteries below 25%:</strong>
<ul>
{% for sensor in low_batteries %}
<li>{{ sensor.attributes.friendly_name | replace(' Battery', '') }}: {{ sensor.state }}%</li>
{% endfor %}
</ul>
{% else %}
All sensor batteries are above 25%
{% endif %}
{% else %}
No battery sensors found or all are unknown/unavailable
{% endif %}
This is what I've tried so far
But this always returns "All sensor batteries are above 25%", even though there are several entities below 25%
try
{% set battery_sensors = states.sensor
| selectattr('entity_id', 'match', '.*_battery$')
| selectattr('state', '!=', 'unknown')
| selectattr('state', '!=', 'unavailable')
| list %}
{% if battery_sensors %}
{% set ns = namespace(low_batteries = []) %}
{% for sensor in battery_sensors %}
{% if sensor.state | int < 25 %}
{% set ns.low_batteries = ns.low_batteries + [sensor] %}
{% endif %}
{% endfor %}
{% if ns.low_batteries %}
<strong>Batteries below 25%:</strong>
<ul>
{% for sensor in ns.low_batteries %}
<li>{{ sensor.attributes.friendly_name | replace(' Battery', '') }}: {{ sensor.state }}%</li>
{% endfor %}
</ul>
{% else %}
All sensor batteries are above 25%
{% endif %}
{% else %}
No battery sensors found or all are unknown/unavailable
{% endif %}
Well there you go, that worked 😄 What did I miss?
You have to use the namespace object to alter variables in a for loop
jinja scope is limited
i.e. you can't access variables outside a loop that are set inside a loop without namespace
Aha! Is that something that has changed? Because I seem to recall this code working previously.
nope
jinja from day 1 has always had that limitation
and when I say day 1, I mean day 1 of jinja, not day 1 of HA
and jinja has been around alot longer than HA
Hum, well thanks a lot for helping out. I've been working on this for a while and chatGPT went in a loop and gave up :p