Templating is an advanced topic for home assistant users which many struggle to leverage.
It allows you to customise and transform entities in home assistant thanks to Jinja2 templating. Templating is expressed with curly brackets and is used in the configuration.yaml to create sensors and in the automation.yaml to create automations.
The best way to learn templating is to experiment in the developer tools, third tab templating. In this way you don’t need to reboot home assistant and get frustrated with error messages.
Loops
In this example I’m going to show you how to create a sensor that will give us a comma delimited string with entity name and battery level.
First of all this is how to create a loop:
# simple loop on all sensors
{% for state in states.sensor %}
{{ state.entity_id }}={{ state.state }}
{% endfor %}
In the loop above the keywords are “for” and “in” which means for each state within the list to all states of a sensor, then on line 2 we output the property entity_id and the property state. The first gives us the Name and the second the value.
We always close a loop with and endfor
Filter battery devices only
From our basic loop above we need to add a few factors, first we are going to look at the attribute device class and check that is has a battery.
Second of all we are excluding all devices that are above a certain % (example 20%).
{% set output = namespace(sensors=[]) %}
{% for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') %}
{% if 0 <= state.state | int(-1) < 20 | int %}
{% set output.sensors = output.sensors + [state.name ~ ' (' ~ state.state ~ ' %)'] %}
{% endif %}
{% endfor %}
Check the battery for {{ output.sensors|join(', ')}}
This code followed by a pipe | looks for the attribute device class.
| selectattr('attributes.device_class', '==', 'battery')
This code excludes any unknown values by converting int values to -1 and then comparing to the threshold (20)
if 0 <= state.state | int(-1) < 20 | int
Now we are adding the results to an array:
{% set output.sensors = output.sensors + [state.name ~ ' (' ~ state.state ~ ' %)'] %}
At the end we are adding a statement to print the output.snsors with a join filter to concatenate everything together separated by a “,”