GENWiki

Premier IT Outsourcing and Support Services within the UK

User Tools

Site Tools


opensource:macros

Macro's allow your Jinja2 Template to have home grown functions

This is great, since Home assistant (at the time of writing) doesn't support jinja2 filters (without stuffing distribution files), so let's take a look at a great macro example:

truncate255. You may know that the maximum size of a state is 255 characters, so a helper such as input_text.tinytext can ONLY be up to 255, if it goes over, it breaks.

That's fine, but with some integrations, like the weather forecast, you can't guarantee its less than 255, although in all probability it will be most of the time. Hence the need for a macro, and then to use this macro in several places as required.

To use public macro's that you can call from any template, create a folder in the config directory called 'custom_templates'. In that create a file call macros.jinja (it doesn't really matter what you call this file, just remember to replace macros.jinja with your filename in the rest of the walkthrough - and you can have multiple files if needed.

An example of a really useful macro:

  1. {% macro truncate255(string) %}
  2. {% set max_length = 255 %}
  3. {% if string | length > max_length %}
  4. {% set truncated = string[:max_length] %}
  5. {% set last_space = truncated.rfind(' ') %}
  6. {% if last_space > 0 %}
  7. {{ truncated[:last_space] }} blah blah blah
  8. {% else %}
  9. {{ truncated }} Blah Blah Blah
  10. {% endif %}
  11. {% else %}
  12. {{ string }}
  13. {% endif %}
  14. {% endmacro %}

Here we can see that we've created a macro (so a function) called truncate255, which takes a string.

If that string is less than 255, it just returns the string intact, but if its over 255 characters it truncates it at the last word break, and then appends blah blah blah. You can of course change this to do whatever you want, maybe just append … for example.

Now in our template, we'd use it like this:

  1. {% from 'tools.jinja' import truncate255 %}
  2. {{ truncate255(states('sensor.metoffice_regionalforecast')) }}

Now don't go copy/pasting and expect that to work, it probably won't, but its an example, and in this example the input sensor.metoffice_regionalforecast sucks the regional forecast from the metoffice datapoint service, mostly <255 long but sometimes not. Now in our template if its longer, it will truncate it at a word boundary and append blah blah blah.

Now you can use this structure for anything, everything, this is just a how-to use the macro feature.

/home/gen.uk/domains/wiki.gen.uk/public_html/data/pages/opensource/macros.txt · Last modified: 2024/02/21 17:48 by genadmin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki