From 50fedcd03b480c49b7b16503e976b2106a802b05 Mon Sep 17 00:00:00 2001 From: Mike Degatano Date: Sun, 27 Mar 2022 11:20:12 -0400 Subject: [PATCH] Mention short-circuiting issue in `iif` (#22092) --- source/_docs/configuration/templating.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/source/_docs/configuration/templating.markdown b/source/_docs/configuration/templating.markdown index 941404c43e9..7d72fd79f3f 100644 --- a/source/_docs/configuration/templating.markdown +++ b/source/_docs/configuration/templating.markdown @@ -372,6 +372,14 @@ Examples using `iif`: {{ (states('light.kitchen') == 'on') | iif('Yes', 'No') }} ``` +
+ +The immediate if filter does not short-circuit like you might expect with a typical conditional statement. The `if_true`, `if_false` and `if_none` expressions will all be evaluated and the filter will simply return one of the resulting values. This means you cannot use this filter to prevent executing an expression which would result in an error. + +For example, if you wanted to select a field from `trigger` in an automation based on the platform you might go to make this template: `trigger.platform == 'event' | iif(trigger.event.data.message, trigger.to_state.state)`. This won't work because both expressions will be evaluated and one will fail since the field doesn't exist. Instead you have to do this `trigger.event.data.message if trigger.platform == 'event' else trigger.to_state.state`. This form of the expression short-circuits so if the platform is `event` the expression `trigger.to_state.state` will never be evaluated and won't cause an error. + +
+ {% endraw %}