Custom Jinja2 filters?

templates
jinja2
Tags: #<Tag:0x00007f0583e7a268> #<Tag:0x00007f0583e7a038>

#1

Hi, are custom Jinja2 filters possible within HA?

I’m wanting to implement the following:

def suffix (d):
    """Returns a suffix for a given number."""
    sfx = {
        1: 'st',
        2: 'nd',
        3: 'rd'
    }
    return 'th' if 11 <= d <= 13 else sfx.get(d%10, 'th')

Taken from here: http://www.joshuakehn.com/2014/8/15/jinja2-template-filters.html

This is to help my waste bin collection integration here:


#2

Yes, only if you have hassbian and can access home assistants py files:

whereverHAisInstalled/HA/helpers/template.py

You add your templates in that file. But every time you update HA, it will get wiped.

If you aren’t using it a lot you could also make a macro that does the same thing:

{%- macro suffix(d) %}
{%- set sfx = {1:'st',2:'nd',3:'rd'} %}
{{- 'th' if 11 <= d <= 13 else sfx.get(d%10, 'th') }}
{%- endmacro %}

But you’d need to place the macro everywhere you use it. Example:

{%- macro suffix(d) %}
{%- set sfx = {1:'st',2:'nd',3:'rd'} %}
{{- 'th' if 11 <= d <= 13 else sfx.get(d%10, 'th') }}
{%- endmacro %}
{% for i in range(1,100) %}
{{- i }}{{ suffix(i) }}
{% endfor %}

#3

This works perfect for what I want to do, many thanks:

{%- macro suffix(d) %}
{%- set sfx = {1:'st',2:'nd',3:'rd'} %}
{{- 'th' if 11 <= d <= 13 else sfx.get(d%10, 'th') }}
{%- endmacro %}

{% set day = as_timestamp(states.calendar.waste_collection.attributes.start_time) | timestamp_custom('%A') %}
{% set date = as_timestamp(states.calendar.waste_collection.attributes.start_time) | timestamp_custom('%d') |int %}

{{ day }} {{ date }}{{ suffix(date) }}

The difficulty now is adding it to my value_template of my sensor. How would I add multi line Jinja like the above?.

EDIT: worked it out using the > function :slight_smile:

  waste_collection_date:
    friendly_name: 'Collection Date'
    value_template: >
       {%- macro suffix(d) %}
       {%- set sfx = {1:'st',2:'nd',3:'rd'} %}
       {{- 'th' if 11 <= d <= 13 else sfx.get(d%10, 'th') }}
       {%- endmacro %}
       {% set day = as_timestamp(states.calendar.waste_collection.attributes.start_time) | timestamp_custom('%A') %}
       {% set date = as_timestamp(states.calendar.waste_collection.attributes.start_time) | timestamp_custom('%d') |int %}
       {{ day }} {{ date }}{{ suffix(date) }}
    icon_template: mdi:calendar-star

Bin / Waste Collection