Template Sensor Syntax Error

I am really struggling to get a simple template sensor working. I have based this on other, working sensors that I have and also followed the example in the documentation but I am still getting this error when I check the configuration:

invalid template (TemplateSyntaxError: expected token ',', got 'string') for dictionary value @ data['sensors']['lounge_door_status']['value_template']. Got "{% if is_state(binary_sensor.lounge_door','on') %}\n  open\n{% else %}\n  closed\n{% endif %}"

This is the sensor code:

- platform: template
  sensors:
    lounge_door_status:
      friendly_name: Lounge Door Status
      icon_template: >-
        {% if is_state('binary_sensor.lounge_door', 'on') %}
          mdi:door-open
        {% else %}
          mdi:door-closed
        {% endif %}
      value_template: >-
        {% if is_state(binary_sensor.lounge_door', 'on') %}
          open
        {% else %}
          closed
        {% endif %}

I’m sure it’s something simple but I can’t for the life of me figure it out.

You forgot a single quote before the word binary_sensor.

{% if is_state(binary_sensor.lounge_door', 'on') %}

Should be this:

{% if is_state('binary_sensor.lounge_door', 'on') %}

Thank you so much, I have been staring at that for about an hour not able to see what was wrong. Now I feel stupid :smiley:

1 Like

You can also used an inline if statement to streamline the template.

- platform: template
  sensors:
    lounge_door_status:
      friendly_name: Lounge Door Status
      icon_template: >
        mdi:door-{{ 'open' if is_state('binary_sensor.lounge_door', 'on') else 'closed' }}
      value_template: >
        {{ 'open' if is_state(binary_sensor.lounge_door', 'on') else 'closed' }}

Better yet, add device_class: door to the configuration of binary_sensor.lounge_door and then you won’t even need this Template Sensor.

The addition of the door device_class will automatically display the door’s states as open/closed and display the correct icon.

3 Likes

Thanks for the suggestions, especially the device class. I didn’t like the icons that were used for open and closed, but I didn’t know that the device_class attribute would change them. Changing it to door has fixed that and negated the need for the sensor.

Cheers