More efficient else if statement for template sensor

Hi all,
I have a working template sensor with the code below. I’m wondering if there’s a better way to write the IF statements. To give you a background, the sensor is a way for me to pull various location data into a single sensor. The IF statements are a way of testing i the user is within one of the predefined zones, otherwise the sensor will report an Open Street Map location instead.

  - name: becks_location_amalgamated
    state: >-
      {% if is_state('sensor.becks_location', 'Home') %}
        {{ states('sensor.becks_location') }}
      {% elif is_state('sensor.becks_location', 'School') %}
        {{ states('sensor.becks_location') }}
      {% elif is_state('sensor.becks_location', 'Sally and Stus') %}
        {{ states('sensor.becks_location') }}
      {% elif is_state('sensor.becks_location', 'Stuart and Lyndas') %}
        {{ states('sensor.becks_location') }}
      {% elif is_state('sensor.becks_location', 'Swimming') %}
        {{ states('sensor.becks_location') }}
      {% elif is_state('sensor.becks_location', 'Tony and Annes') %}
        {{ states('sensor.becks_location') }}
      {% elif is_state('sensor.becks_location', 'Ross Work') %}
        {{ states('sensor.becks_location') }}
      {% else %}
        {{ state_attr('sensor.becks_location_open_street_map', 'locality') }}
      {% endif %}

Im under the assumption there may be a better way of testing if a user is inside one of the pre-defined zones, or at the very least there will be a way of tidying up the rather long ELSE IF code. I’m worried that if I rename a zone or add new ones that I may forget to update the sensor.
I’m not great at code or editing it so any help anyone can pass on is greatly appreciated

Thanks

You can do one if with one else by doing:

state('sensor.becks_location') in ['Home', 'School', ... ]

If you want to include all your defined zones you can use:

{% if states('sensor.becks_location') in (expand(states.zone)|map(attribute='name')|list) + ["home"] %}
  {{ states('sensor.becks_location') }}
{% else %}
  {{ state_attr('sensor.becks_location_open_street_map', 'locality') }}
{% endif %}

You can also put specific zones you want to track into a group…

{% if states('sensor.becks_location') in (expand('group.tracked_zones')|map(attribute='name')|list) + ["home"] %}...

1 Like

that’s brilliant, thanks!!