How to set icon of binary_sensor depend on its state?

Hello. I tried to change the name and the icon of binary_sensor depend on its state (on and off). This is my code

          - entity: binary_sensor.door_window_sensor_158d0002b7b0c0
            name_template: >-
             {% if binary_sensor.door_window_sensor_158d0002b7b0c0.state == 'on' %}
              test1
             {% else %} 
              test2
             {% endif %}
            
            icon_template: >
             {% if binary_sensor.door_window_sensor_158d0002b7b0c0.state == 'on' %}
               mdi:lightbulb-on
             {% else %}
               mdi:lightbulb
             {% endif %}

but it’s not working. Any one help me with correct code please?

You need to add the states prefix to your entity >

states.binary_sensor.door_window_sensor_158d0002b7b0c0.state

Also, note from the documentation that you may want to consider using is_state instead because it will not create an error if the component your sensor uses hasn’t fully loaded at startup. In this case you would use:

      - entity: binary_sensor.door_window_sensor_158d0002b7b0c0
        name_template: >-
         {% if is_state('binary_sensor.door_window_sensor_158d0002b7b0c0', 'on') %}
          test1
         {% else %} 
          test2
         {% endif %}
        
        icon_template: >
         {% if is_state('binary_sensor.door_window_sensor_158d0002b7b0c0', 'on') %}
           mdi:lightbulb-on
         {% else %}
           mdi:lightbulb
         {% endif %}

I also highly recommend the template editor within Home Assistant for troubleshooting!

1 Like

P.S. - I’m not sure about that name_template that you’re using. I’ve never done that before to know if/how it works.

1 Like

I tried your code but not working. As I 've just know may be the Lovelace UI cannot accept to change the icon depend on the state. May be I have to create new sensor template with icon on it and after that use Lovelace to show the sensor.

From your original post I didn’t realize this was in your Lovelace config - yes I would probably make a template sensor with this if the sensor itself doesn’t support icon templates.