Custom Jinja2 filters?

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: Jinja2 Template Filters | Joshua Kehn

This is to help my waste bin collection integration here:

1 Like

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 Likes

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
3 Likes