I often find myself writing templates where a ternary function would be helpful. In fact, I installed this HACS package to enable the use of ternary operations in template strings. Would be lovely to have as a first-party function
Syntax:
iif(condition, if_true, if_false, if_none)
{{ iif(is_state('switch.foo', 'on'), 'green', 'red') }}
1 Like
fyi you can use a normal in-line if statement too
{{ 'a' if a else 'b' }}
and it can be chained as long as you want to go
{{ 'a' if a else 'b' if b else 'c' if c else 'd' }}
Using this over iif
also ensures that the results are not resolved until they are accessed. With iif
all results are resolved during the resolution of the trigger. So if you’re accessing nested attributes that don’t exist, iif
will produce an error where in-line if statements wont.
I.e. This will error if something.b
doesn’t exist
{{ if(a, 'a', something.b) }}
where this wont
{{ 'a' if a else something.b }}
1 Like