I’ve been experimenting with template sensors in Home Assistant to create a more intuitive and visually appealing interface. One feature I wanted to implement was dynamic icons that change based on the sensor’s state. For example, showing a fan icon when the fan is on and a fan-off icon when it’s off. This would make the interface more user-friendly and immediately informative at a glance.
Initially, I tried using the icon_template within the template sensor configuration. Here’s the setup I used:
yaml
sensor:
- platform: template
sensors:
hvac_fan_action:
friendly_name: “Fan Status”
value_template: “{{ state_attr(‘climate.thermostat_xx_xx_xx’, ‘fan_action’) }}”
icon_template: >-
{% if is_state(hvac_fan_action, ‘on’) %}
mdi:fan
{% else %}
mdi:fan-off
{% endif %}
However, I encountered an issue where the icon always defaulted to the else state, regardless of the actual value of fan_action. I tried several variations, including different syntax for the if statement and adjusting the quotes around the state value, but nothing seemed to work. This was frustrating because the logic appeared sound, and I couldn’t pinpoint the error.
After some research, I discovered that the is_state function might not be the best approach in this context. Instead, I switched to using state_attr directly within the if condition. Here’s the revised configuration:
yaml
sensor:
- platform: template
sensors:
hvac_fan_action:
friendly_name: “Fan Status”
value_template: “{{ state_attr(‘climate.thermostat_xx_xx_xx’, ‘fan_action’) }}”
icon_template: >-
{% if state_attr(‘climate.thermostat_xx_xx_xx’, ‘fan_action’) == ‘on’ %}
mdi:fan
{% else %}
mdi:fan-off
{% endif %}
This adjustment finally worked! The icons now dynamically update based on the fan’s state, providing a clear visual cue without requiring users to hover over the sensor to check the value. This small enhancement has made a significant difference in the usability of my Home Assistant setup.
I encourage others who are looking to implement similar dynamic icons to experiment with different template configurations and not be discouraged by initial setbacks. The Home Assistant community is incredibly supportive, and resources like the forums and documentation are invaluable for troubleshooting and learning.