Hey everyone! I’ve been diving into some template expressions in Home Assistant and came across something interesting with the iif() function. I wanted to share my findings and see if others have encountered similar behavior or can shed some light on it.
So, here’s the setup: I’m using iif() to handle different states of an entity. In the first example, I have a button entity that sometimes returns unknown or unavailable. The expression works perfectly, evaluating to now() when the state is unknown or unavailable, and no errors pop up. That’s exactly what I expected.
Here’s the working expression:
python
{% set start = states(‘button.hvac_filter_reset’) %}
{{ iif(start in [‘unknown’,‘unavailable’],now(),start|as_datetime) }}
Now, the second example is where things get a bit puzzling. I tried a similar structure with a media player entity, but it throws an UndefinedError: list object has no element 1. Here’s the problematic expression:
python
{% set media_player = ‘’ %}
{{ iif(media_player == ‘’,‘’,media_player.split(‘.’)[0] ~ ‘.mass_’ ~ media_player.split(‘.’)[1]) }}
I expected this to evaluate to an empty string when media_player is empty, but instead, it errors out. After some troubleshooting, I found a workaround using an if statement:
python
{% if media_player != ‘’ %}
{{ media_player.split(‘.’)[0] ~ ‘.mass_’ ~ media_player.split(‘.’)[1] }}
{% endif %}
This works without issues, but I’m still curious why the iif() function behaves differently in these two scenarios. In the first case, the false part of the expression isn’t evaluated when the condition is true, which is correct. However, in the second case, it seems like the false part is still being evaluated, leading to the error.
Has anyone else noticed this behavior with iif()? Am I missing something about how iif() evaluates its arguments? I’d love to understand this better to avoid similar issues in the future. Maybe there’s a more efficient way to structure these expressions to prevent unintended evaluations.
Let me know your thoughts or if you’ve encountered something similar! Happy automating! ![]()