I’m overengineering again!
What I want to do is convert my Weather Alerting system which provides its output as words … “Green”, “Yellow”, “Orange”, “Red”
I want to change this to a numeric value 0-3 or 1-4 so that I can use a gauge card to present this info.
Is there an equivalent of a CASE statement for templates … something like
CASE
"Green"
set alertvariable to 0
"Yellow"
set alertvariable to 1
"Orange"
set alertvariable to 2
"Red"
set alertvariable to 3
END CASE
Note that this will raise an error if the sensor does not match one of the four colours, unlike the get() version which returns null.
Just to show that there are lots of ways of achieving the result, here are some options for trying out in the Template Editor, where c is your sensor, including a stupid code golf one. All four options cope with an offline sensor (unknown or unavailable) in differing ways:
{% set c = "Green" %}
# Drew's get() solution: returns None if offline
{{ {'Green': 0, 'Yellow': 1, 'Orange': 2, 'Red': 3}.get(c) }}
# List lookup: returns 4 or 5 if offline
{{ ['Green', 'Yellow', 'Orange', 'Red', 'unknown', 'unavailable'].index(c) }}
# String lookup of first character: returns 4 if offline
{{ 'GYORu'.index(c.0) }}
# Playing games with character codes: returns 1 if offline
{{ c.0|ord%14//4 }}
Oops, I read the topic through Google Translator and the translation is not always correct.
I assumed that in Python array “key => values” it was my mistake.
There is no need to open a new topic, now those who are looking for information will see an error. Thank you
Just going to add on to this thread for anyone else that came here from a Google search. You can actually have a “case-like” statement in a single template expression if you make use of Python’s ternary expression syntax.
For example, if you have a variable thing that’s set to Apple, and you run this template:
{{ 'A Banana' if 'banana' in (thing | lower) else
'An Apple' if 'apple' in (thing | lower) else
'An Orange' if 'orange' in (thing | lower) else
'A Pear' if 'pear' in (thing | lower)
else 'Not Sure' }}