Okay, I’ll ask another question then: should we not use the macro feature of Jinja at all then in Home Assistant?
Well, it works, but the idea of a function is to be able to use it anywhere.
Several Mushroom cards allow the use of templates but unfortunately, there’s no entities (plural) card in the Mushroom collection.
So I use a default lovelace entities card together with the secondary-entity-row add-on which allows for templates in the secondary information of an entity in an entities card.
My use case is: I want to list ~30 (German) holiday dates. I use the Calendarific integration to create the sensors. They contain the number of days until the holiday. In the entities card I additionally want to display the exact date of that sensor, which is an attribute of the sensor. This works fine, in English:
The yaml code for the entities in the entities card looks like this for the first 3 of ~30 entities:
- entity: sensor.cal_valentine_s_day
type: custom:secondaryinfo-entity-row
secondary_info: >-
{{ as_timestamp(state_attr('sensor.cal_valentine_s_day', 'date')) |
timestamp_custom('%A, %d.%m.%Y') }}
- entity: sensor.cal_rosenmontag
type: custom:secondaryinfo-entity-row
secondary_info: >-
{{ as_timestamp(state_attr('sensor.cal_rosenmontag', 'date')) |
timestamp_custom('%A, %d.%m.%Y') }}
- entity: sensor.cal_st_patrick_s_day
type: custom:secondaryinfo-entity-row
secondary_info: >-
{{ as_timestamp(state_attr('sensor.cal_st_patrick_s_day', 'date')) |
timestamp_custom('%A, %d.%m.%Y') }}
If I want the weekday names in German I can use the tip you, @123, gave me. But because I don’t want to repeat that weekday names array and the additional code ~30 times for each date sensor entity in its secondary_info (it would look like this for every row:
{{ ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'][as_datetime(state_attr('sensor.cal_karfreitag', 'date')).weekday()] }}, {{ as_datetime(state_attr('sensor.cal_karfreitag', 'date')).strftime('%d.%m.%Y') }}
), I thought I’d define this macro once …
{% macro formatted_date(datesensorname) -%}
{% set thedate = as_datetime(state_attr(datesensorname, 'date')) %}
{{
['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'][thedate.weekday()]
}}, {{ thedate.strftime('%d.%m.%Y') }}
{%- endmacro %}
… and have the individual lines of the entities card look like this then:
- entity: sensor.cal_valentine_s_day
type: custom:secondaryinfo-entity-row
secondary_info: {{ formatted_date('sensor.cal_valentine_s_day') }}
Much shorter.
I don’t have a problem defining template sensors inside my configuration.yaml
in the template:
section. But as long as I can’t use that macro there, neither, I have nothing gained because I still have to write that long definition with the weekday names ~30 times, for each template sensor. Which is … quite … annoying … and … dumb.
So, there’s my specific use case. Eager to know what I can do about it.