An easy way to add templating support to your custom front end projects!

I recently was asked to add templating support to a couple of my Home Assistant front end projects. At first I tried copying what button-card and card-mod were doing, but both implementations were hard to follow and copy.

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 simple 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.

To use this package, 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!

What’s the catch?

There is one major caveat. I have to re-implement the Home Assistant template extensions in TypeScript in order for them to be used. I’ve already gotten the important state ones done (updated list in the README) and will implement more over time as they’re requested.

That’s where I’m hoping y’all come in! In addition to using this package in your projects, I’ve created a pull request template in the repository so the custom card developer community can help implement the Home Assistant template functions (and others that may be useful, like match_media for media queries).

2 Likes