What I’m trying to do is calculate the percentage of current temperature within the range of today’s forecast’s high and low, then choose a colour from a defined range and set the icon to the colour.
For example, the colour ranges from #12c2e9
at 0% to #f64f59
at 100%. Their respective RGB values are (18, 194, 233)
and (246, 79, 89)
. I also want the midpoint to be white-ish (240, 240, 240)
.
So I derived a formula to get the RGB value for a given percentage. Let’s say the percentage is p
.
if p <= 0.5:
r = 18 + p * (240 - 18)
g = 194 + p * (240 - 194)
b = 233 + p * (240 - 233)
else:
r = 240 + p * (246 - 240)
g = 240 + p * (79 - 240)
b = 240 + p * (89 - 240)
and with Home Assistant’s template:
{% set p=((states("input_number.test_slider")|int)/100) %}
{% set r_max=246 %}
{% set g_max=79 %}
{% set b_max=89 %}
{% set r_mid=240 %}
{% set g_mid=240 %}
{% set b_mid=240 %}
{% set r_min=18 %}
{% set g_min=194 %}
{% set b_min=233 %}
{% if p <= 0.5 %}
{{ '#%02x%02x%02x' | format((r_min + p * (r_mid - r_min)) | int, (g_min + p * (g_mid - g_min)) | int , (b_min + p * (b_mid - b_min)) | int) }}
{% else %}
{{ '#%02x%02x%02x' | format((r_mid + p * (r_max - r_mid)) | int, (g_mid + p * (g_max - g_mid)) | int , (b_mid + p * (b_max - b_mid)) | int) }}
{% endif %}
which gives me hex value based on the percentage p
.
However, when I implement this into the card:
type: custom:mushroom-number-card
entity: input_number.test_slider
icon_color: >-
{% set p=((states("input_number.test_slider")|int)/100) %}
{% set r_max=246 %}
{% set g_max=79 %}
{% set b_max=89 %}
{% set r_mid=240 %}
{% set g_mid=240 %}
{% set b_mid=240 %}
{% set r_min=18 %}
{% set g_min=194 %}
{% set b_min=233 %}
{% if p <= 0.5 %}
{{ '#%02x%02x%02x' | format((r_min + p * (r_mid - r_min)) | int, (g_min + p * (g_mid - g_min)) | int , (b_min + p * (b_mid - b_min)) | int) }}
{% else %}
{{ '#%02x%02x%02x' | format((r_mid + p * (r_max - r_mid)) | int, (g_mid + p * (g_max - g_mid)) | int , (b_mid + p * (b_max - b_mid)) | int) }}
{% endif %}
the icon colour of the card stays white, regardless of the value of the slider.
I’ve searched high and low for this, but I can’t really seem to find anything useful. There are lots of example for icon_color
based to states with simple {% if %}{% endif %}
, but not for more complex ones like this.
Can anyone help me with this?