Add doc for new contains jinja filter and test (#25890)

This commit is contained in:
Vaarlion 2023-01-25 11:51:55 +01:00 committed by GitHub
parent 7fc6c86abf
commit bc068381df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -706,6 +706,32 @@ Closest to some entity:
{% endraw %}
### Contains
Jinja provides by default a [`in` operator](https://jinja.palletsprojects.com/en/latest/templates/#other-operators) how return `True` when one element is `in` a provided list.
The `contains` test and filter allow you to do the exact opposite and test for a list containing an element. This is particularly useful in `select` or `selectattr` filter, as well as to check if a device has a specific attribute, a `supported_color_modes`, a specific light effect.
Some examples:
{% raw %}
- `{{ state_attr('light.dining_room', 'effect_list') | contains('rainbow') }}` will return `true` if the light has a `rainbow` effect.
- `{{ expand('light.office') | selectattr("attributes.supported_color_modes", 'contains', 'color_temp') | list }}` will return all light that support color_temp in the office group.
- ```text
{% set current_month = now().month %}
{% set extra_ambiance = [
{'name':'Halloween', 'month': [10,11]},
{'name':'Noel', 'month': [1,11,12]}
]%}
{% set to_add = extra_ambiance | selectattr('month', 'contains', current_month ) | map(attribute='name') | list %}
{% set to_remove = extra_ambiance | map(attribute='name') | reject('in', to_add) | list %}
{{ (state_attr('input_select.light_theme', 'options') + to_add ) | unique | reject('in', to_remove) | list }}
```
This more complex example uses the `contains` filter to match the current month with a list. In this case, it's used to generate a list of light theme to give to the `Input select: Set options` service.
{% endraw %}
### Numeric functions and filters
Some of these functions can also be used in a [filter](https://jinja.palletsprojects.com/en/latest/templates/#id11). This means they can act as a normal function like this `sqrt(2)`, or as part of a filter like this `2|sqrt`.