Is there a more elegant way to template this?

Hey guys,

Tried searching online but couldnt find anything but Im sure there must be a cleaner way of templating this?

{{ 
is_state('sensor.home_x_direction_of_travel', "towards") or
is_state('sensor.home_y_direction_of_travel', "towards") or
is_state('sensor.home_z_direction_of_travel', "towards") or
is_state('sensor.home_x_direction_of_travel', "away_from") or
is_state('sensor.home_y_direction_of_travel', "away_from") or
is_state('sensor.home_z_direction_of_travel', "away_from") 

}}

Hi Carl,

If this is part of an automation that is triggered by one of those sensors, you could just check the trigger entity state for one of those results.

More context might get you a better answer, otherwise you are here:

How to help us help you - or How to ask a good question.

Are you by any chance trying to recreate the proximity sensor behavior? In that case, the integration is the most elegant :wink:

There’s also the device_tracker attribute for speed if you just want to see movement.

Thanks for the replies.

Im making a tenplate sensor that will be true if any of the above are true. When the sensor is true it will trigger an automation and the automation runs only whilst the sensor is true if that makes sense?

Eh, if you consider this more elegant

{{ ['x', 'y', 'z'] | map('center', 3) | map('replace',' ', '%s') | map('format', 'sensor.home_', '_direction_of_travel') | select('is_state', ['towards','away_from']) | list | count > 0 }}
2 Likes

Improving on yours:

{{ (['sensor.home_%s_direction_of_travel']*3) | format(*['x','y','z']) | select('is_state', ['towards','away_from']) | list | count > 0 }}
1 Like

Beautiful. Could reduce it with format(*'xyz'); and I think the template editor might be messing with you in terms of what’s a list and what’s a string. My version:

{{ (('sensor.home_%c_direction_of_travel,'*3)|format(*'xyz')).split(',')|map('states')|select('in',['towards','away_from'])|list|count>0 }}
2 Likes

Never get involved in a land war in Asia; never challenge Troon when jinja code golf is on the line

1 Like