Hello,
I’m still trying to optimize the readability of my code and its maintainability.
Then I’m asking myself if there is a way to create custom global functions for JINJA templates.
For example, in my home assistant, I’m customizing temperature badges based on a coloured scale.
Therefor I’m repeating a dozen of time (for each temp badges) the same portion of code below :
- type: state-label
entity: sensor.my_temp
name: MyTempSensor
style: |
:host {
{% set state = states('sensor.my_temp') | float %}
{% set text = 'white' %}
{% if state < -23 %} {% set color = 'Magenta' %}
{% elif state >= -23 and state < -18 %} {% set color = 'Purple' %}
{% elif state >= -18 and state < -12 %} {% set color = 'DarkMagenta' %}
{% elif state >= -12 and state < -7 %} {% set color = 'Blue' %}
{% elif state >= -7 and state < -1 %} {% set color = 'Skyblue' %}
{% elif state >= -1 and state < 4 %} {% set color = 'Green' %}
{% elif state >= 4 and state < 10 %} {% set color = 'GreenYellow' %}
{% elif state >= 10 and state < 16 %} {% set color = 'Yellow' %} {% set text = 'black' %}
{% elif state >= 16 and state < 23 %} {% set color = 'Orange' %}
{% elif state >= 23 and state < 27 %} {% set color = 'Red' %}
{% elif state >= 27 and state < 32 %} {% set color = 'GreenYellow' %}
{% elif state >= 32 and state < 38 %} {% set color = 'DarkRed' %}
{% elif state >= 38 %} {% set color = 'Maroon' %}
{% else %} {% set color = 'grey' %}
{% endif %}
color: {{ color }};
--label-badge-red: {{ color }};
--ha-label-badge-label-color: {{ text }};
}
Well… it works, but it’s painful in terms of maintainability. The problem is : if now I decide to change my scale color schema, then I need to go everywhere and modify it.
Search & replace is my best friend, but I assume there should exist a better way to do that?
Anyone has a clever solution to avoid repeating the same code again and again?
Many thanks in advance.