Nerwyn / ha-nunjucks

Wrapper for nunjucks for use with Home Assistant frontend custom components to render templates.
Apache License 2.0
7 stars 0 forks source link

Ability to add custom context #1

Closed pgorod closed 10 months ago

pgorod commented 10 months ago

Currently, only some HASS context is available to the template. But it would be useful to be able to add more arbitrary context, including full objects, to be made available inside the template.

Something like this:

ha-nunjucks.addContext({ username: 'James' });
ha-nunjucks.addContext({ goes: 'here' });
ha-nunjucks.addContext({ tasklist: someObject });
ha-nunjucks.render('the template text goes {{ goes }}, using any parts of the context it wants');

For reference, here's the forum thread that started this suggestion.

Thanks!

Nerwyn commented 10 months ago

Added in v1.2.0

import { renderTemplate } from 'ha-nunjucks';

const context = {
  foo: 'bar',
  doThing(thing: string) {
    return `doing ${thing}!`;
  },
};

const renderedString = renderTemplate(this.hass, templateString, context);
pgorod commented 10 months ago

Wow! 🎉

I'm curious about that doThing thing... how would that be used in a template? And what possible uses do you see for adding a function as context? Is that like extending the template syntax?

Thanks, I am impressed!

Nerwyn commented 10 months ago

The same way you'd use Home Assistant templating functions like is_state:

import { renderTemplate } from 'ha-nunjucks';

const context = {
  foo: 'bar',
  doThing(thing: string) {
    return `doing ${thing}!`;
  },
};

const templateString = '{{ doThing("my taxes") }}';
const renderedString = renderTemplate(this.hass, templateString, context);
console.log(renderedString);

> doing my taxes!

It's up to developers to decide what to do with it. It is extending the templating syntax.

pgorod commented 10 months ago

Thanks for the explanation, I will explore this.