2023.4: Finialize template macros

This commit is contained in:
Franck Nijhof 2023-04-05 14:29:53 +02:00
parent b3230231ec
commit 6eb702c346
No known key found for this signature in database
GPG Key ID: D62583BA8AB11CA3

View File

@ -177,22 +177,13 @@ Note: This is a temporary placeholder screenshot. Needs replacement.
## Macros for your templates ## Macros for your templates
{% details "TODO" %} If you are an advanced Home Assistant user, you most likely will be familiar
with Home Assistant's templating language: Jinja2. It allows you to do amazing
- Improve/extend story powerful things in your templates. However, if you have lots of them, you
- Proof read/spelling/grammar often end up repeating similar logic everywhere!
- Replace macro with something more useful?
- Link to docs
{% enddetails %}
If you are into writing templates, you will be very familiar with the templating
language Home Assistant uses: Jinja. It allows you to do amazing powerful things
in your templates. However, if you have lots of templates, you often end
up repeating similar logic everywhere!
[@depoll] to the rescue! He found a way to add the ability to centrally define [@depoll] to the rescue! He found a way to add the ability to centrally define
your Jinja macros and import and use them anywhere in Home Assistant! 🤯 your own Jinja2 macros and import and use them anywhere in Home Assistant! 🤯
To support this, Home Assistant now has a new `custom_templates` folder, where To support this, Home Assistant now has a new `custom_templates` folder, where
you can store your macros. For example, assume this file you can store your macros. For example, assume this file
@ -201,22 +192,25 @@ you can store your macros. For example, assume this file
{% raw %} {% raw %}
```jinja ```jinja
{% macro is_on(entity_id) %} {% macro answer_question(entity_id) %}
Is the {{ state_attr(entity_id, 'friendly_name') }} on? Is the {{ state_attr(entity_id, 'friendly_name') }} on?
{{ (states(entity_id) == 'on') | iif('Yes', 'No') }}! {{ (states(entity_id) == 'on') | iif('Yes', 'No') }}!
{% endmacro %} {% endmacro %}
``` ```
{% endraw %} {% endraw %}
This macro `is_on` will ask and answer a question based on a given entity ID. This macro `answer_question` will ask and answer a question based on a given
You can now import and use this macro anywhere in Home Assistant. For example: entity ID. You can now import and use this macro anywhere in Home Assistant.
For example:
{% raw %} {% raw %}
```jinja ```jinja
{% from 'tools.jinja' import is_on %} {% from 'tools.jinja' import answer_question %}
{{ is_on('light.kitch') }} {{ answer_question('light.kitchen') }}
``` ```
{% endraw %} {% endraw %}
@ -228,7 +222,9 @@ Is the kitchen light on?
Yes! Yes!
``` ```
An amazing contribution, thank you [@depoll]! An fantastic contribution! Thank you, [@depoll]!
[Reusing templates documentation](/docs/configuration/templating/#reusing-templates)
[@depoll]: https://github.com/depoll [@depoll]: https://github.com/depoll