Mention short-circuiting issue in iif (#22092)

This commit is contained in:
Mike Degatano 2022-03-27 11:20:12 -04:00 committed by GitHub
parent 7251b080f6
commit 50fedcd03b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -372,6 +372,14 @@ Examples using `iif`:
{{ (states('light.kitchen') == 'on') | iif('Yes', 'No') }} {{ (states('light.kitchen') == 'on') | iif('Yes', 'No') }}
``` ```
<div class='note warning'>
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.
</div>
{% endraw %} {% endraw %}