brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: iif() is the short if/else for Home Assistant templates

Yaml
~/tips/tip-home-assistant-template-iif

iif(condition, if_true, if_false, if_none)

iif() turns a condition into one of two values in a single template expression.

Every time I need a two-word answer from a template, I end up writing a four-line if/else block with endif and all. iif does the same in one expression, and Home Assistant has had it for years.

The signature from the docs looks like this:

iif(condition, if_true, if_false, if_none)

With a condition, a value for true and a value for false, you get one of the two back. The docs show it as a function and as a filter:

{{ iif(states("sensor.temperature") | float > 25, "warm", "cool") }}
{{ is_state("binary_sensor.front_door", "on") | iif("open", "closed") }}

The filter form reads nicely after is_state, because the condition comes first and the two words follow it. Put either one in a notification message or a template sensor and you skip the block syntax completely.

The defaults are True and False, so with only a condition you get a plain boolean back. The fourth argument, if_none, is the value for a condition that is none.

One caveat: both results are plain values, so there is no place for several statements or a set inside. When the logic grows past two outcomes, I’d go back to {% if %} and {% elif %}. The docs say iif exists since Home Assistant 2021.12, so any install you run today has it. Try your expression in Developer Tools, Template, before it goes into an automation.

Further reading: iif in the Home Assistant template functions

More Yaml tips yamllint -f parsable config.yaml yamllint -d relaxed docker-compose.yml Sensor is available Today_at() makes time-of-day checks in Home Assistant templates easy actions: All Yaml tips (10) All topics

Link