A while back I was asked to add templating support to a couple of my Home Assistant frontend projects (Universal Remote Card and Custom Features for Home Assistant Cards). One issue I ran into while implementing was the difficulty of managing template subscriptions and limited custom variable support. Home Assistant templates in frontend cards are sent to the backend, processed using jinja2, and then sent back to the frontend. While this is usually fast, using templates rendered this way synchronously can prove difficult and lead to an initial jumpiness on first load.
After some additional research, I developed a new method which processes Home Assistant templates in the frontend using the hass object.
ha-nunjucks
ha-nunjucks is a wrapper for nunjucks. Nunjucks is a templating engine for JavaScript which is heavily inspired by jinja2 and shares almost all of it’s syntax. Therefore Home Assistant jinja2 templates largely work with nunjucks with little to no modification!
To use this package in your custom frontend projects, install it with npm:
npm install ha-nunjucks
And then import and use the renderTemplate function:
import { renderTemplate } from 'ha-nunjucks';
const renderedString = renderTemplate(this.hass, templateString);
It’s that easy!
You can also add your own variables and functions to the render context using an optional context argument.
const context = {
foo: 'bar',
doThing(thing: string) {
return `doing ${thing}!`;
},
config: {
entity: 'foo.bar',
attribute: 'baz_bah',
},
};
const renderedString = renderTemplate(this.hass, templateString, context);
Every single Home Assistant template extension has been reimplemented in TypeScript in this package, including Pythonic datetimes using a separate project I forked just for ha-nunjucks - ts-py-datetime. If any new ones are added, bugs found, or if you have a neat idea for a good non-standard template extension I’m open to GitHub issues and contributors!
I believe that this method of template rendering is not just at parity with, but is superior to backend jinja2 template rendering for Home Assistant frontend cards. By keeping all of the render logic synchronous and in the frontend, template rendering can now all be done before render in milliseconds if not less. I hope some of y’all consider implementing it into your projects and feel the same!