Template sensor entity Colorcoded

Greetings,

I have a basic template that creates a new sensor with a custom state (based on a switch) instead of using the original switch state. It works great, but I would like to add the functionality to change the color of the new state. Check example below.

sensor garageforrad:
  - platform: template
    sensors:
      garageforrad:
        value_template: '{% if is_state("switch.garageforrad", "on") or is_state("switch.garageforrad", "on") %} #FF0000ÖPPEN {% else %} #00FF00Stängd {% endif %}'
        icon_template: '{% if is_state("switch.garageforrad", "on") or is_state("switch.garageforrad", "on") %} mdi:door-open {% else %} mdi:door {% endif %}'
        friendly_name: Förrådsdörr  

I want the state “ÖPPEN” to be red (FF0000) and the state “Stängd” to be green (00FF00).
The sensor is used inside a lovelace entity card (Maybe I can change the color of a specific entity there?)

Kind regards,

The color can be changed using style in lovelace, you should only have the word (not color) stored in the templates.

There are threads about changing the color when on or off. This would require you to change your sensor to a binary_sensor with a device_class of door. It will set the icon and state for you. You won’t have to specify open/close, nor will you have to choose an icon for opening/closing.

make your value template:

binary_sensor garageforrad:
  - platform: template
    sensors:
      garageforrad:
        value_template: '{{ is_state("switch.garageforrad", "on") }}'
        friendly_name: Förrådsdörr  
        device_class: door

Then, from that point you need to make your style correctly in lovelace. I don’t know how to do that off the top of my head, but I’ve seen threads talk about it recently. Just cruise the Configuration with the tag Frontend and I’m sure you’ll find examples.

Thanks again petro, you helped me so many times I can’t even count the times. Have a great day!

Kind regards,