I’ve been trying DRY up some of my wordier templates a bit now that you no longer have to explicitly write out the name of each entity you want tracked and ran across an unexpected limitation. I feel like there has to be a better way to do this in Jinja but I can’t figure it out for the life of me. Since I know there’s a lot of Jinja wizards on here I’m hoping someone can help me out.
Basically I have a bunch of sensors with a very similar naming convention, group.person_detected_<room name>
. I’m trying to make a sensor which is true when group.anyone
is home
and the person_detected
group is off
for a set of rooms. I originally made the sensor as one long if <state> and <state> and <state> and ...
statement to ensure each entity name was written out. Now since you don’t have to I want to stop repeating the group.person_detected_
part.
I came up with this:
{% set detectors = (['', 'upstairs', 'guest_room', 'bedroom'] | join(' group.person_detected_')).split(' ')[1:] %}
{{ is_state('group.anyone', 'home') and expand(detectors) | selectattr('state', 'eq', 'on') | list | length == 0 }}
This works but its kind of ugly. All I want to do is have an array with a list of room names and then use a filter or function to prefix each element of that array with some text. I couldn’t seem to figure out anyway to do that besides that kind of hacky join
then split
.
So basically, is there a better way to add text to each string element in array in Jinja? Or maybe a custom filter added to Jinja in Home Assistant?