I’ve been using the wonderful lovelace_gen by @thomasloven to assemble my YAML lovelace configuration from a series of files. This is really handy!
Recently, I was playing around with this, and as you might expect, you find yourself doing the same thing over and over for different UI elements. And I wanted to avoid having to repeat all that boilerplate.
And then I remembered that YAML includes the ability to represent data as JSON objects… Hmm… I thought - this was a way to use jinja2 macros in a general way without having to worry about the whitespace indentation level at any particular point.
Let me illustrate with the first part of a lovelace page configuration. It demonstrates 3 ways of representing the same type of lovelace card specification. It begins with a jinja2 macro definition that’s used for the last alternative:
# lovelace_gen
{% macro camera(_entity, _live='auto') -%}
{
"type": "picture-entity",
"camera_view": "{{_live}}",
"entity": "{{_entity}}"
}
{%- endmacro %}
title: Weather
badges: []
panel: true
cards:
- type: vertical-stack
cards:
- type: horizontal-stack
cards:
- type: picture-entity
entity: camera.cam8
- {
"type": "picture-entity",
"entity": "camera.cam7"
}
- {{ camera('camera.cam9') }}
Here there are 3 cameras in picture-entity
cards, within a horizontal-stack
element. The first is defined in the usual way.
The second one just represents the dictionary in JSON syntax. The indentation of the JSON structure is irrelevant! Often you see this style syntax all collapsed on a single line.
The third one uses a macro to generate the same JSON syntax.
So in this way, it ought to be easy to write some jinja2 macros to generate complex lovelace card definitions and incorporate their use in arbitrary places in your lovelace configuration. I started down this path while I was playing around with the powerful custom button-card as a way to augment or replace the templating capability there.