Sensor template for MQTT - State extraction?

Can anyone spot what I’m doing wrong in my syntax? I’ve also tried adding .state to the end, but that didn’t help.

template_garage_door:
    value_template:
      >-
      {%- if is_state('states.sensor.garage_door_status', 'CLOSED') -%}
        Closed
      {%- elif is_state('states.sensor.garage_door_status', 'OPEN') -%}
        Open
      {%- else -%}
        <--- ERROR --->
      {%- endif %}
    icon_template: >-
      {%- if is_state("states.sensor.garage_door_status.state", "CLOSED") -%}
        mdi:garage
      {%- else -%}
        mdi:garage-open
      {%- endif %}
    friendly_name: 'Garage Door Status'

This is the sensor:

- platform: mqtt
  state_topic: "homeassistant/garage/door/status"
  name: "Garage Door Status"
  payload_on: "OPEN"
  payload_off: "CLOSED"

Just to confirm, this is a binary_sensor, right?

If that’s the case, then the states will only be ‘on’ of ‘off’, rather than the ‘OPEN’ and ‘CLOSED’ you’re using in your templates.

Maybe it should look like…

  - platform: template
    sensors:    
      template_garage_door:
        value_template: >-
          {%- if is_state('sensor.garage_door_status', 'CLOSED') -%}
            Closed
          {%- elif is_state('sensor.garage_door_status', 'OPEN') -%}
            Open
          {%- endif %}
      icon_template: >-
        {%- if is_state("sensor.garage_door_status", "CLOSED") -%}
          mdi:garage
        {%- else -%}
          mdi:garage-open
        {%- endif %}
      friendly_name: 'Garage Door Status'

What I provided was just the template_garage_door sensor under my template platform. All my other templates are working fine.

I have a WEMOS D1 that’s getting a door open/close sensor. This updates the MQTT topic with either OPEN or CLOSED. The value shows up for the MQTT sensor no problem, but I’d like to tie it in with the icon template.

I don’t think you need to use state.sensor… and maybe some indentation weirdness? Should just be able to use the entity name like so:

template_garage_door:
  value_template: >-
    {%- if is_state('sensor.garage_door_status', 'CLOSED') -%}
      Closed
    {%- elif is_state('sensor.garage_door_status', 'OPEN') -%}
      Open
    {%- else -%}
      <--- ERROR --->
    {%- endif %}
  icon_template: >-
    {%- if is_state("sensor.garage_door_status", "CLOSED") -%}
      mdi:garage
    {%- else -%}
      mdi:garage-open
    {%- endif %}
  friendly_name: 'Garage Door Status'
1 Like

You, sir, are a genius!

BTW, how do you get syntax highlighting of your code?

Preface (and end) code paragraphs with three backticks!