Closed pgorod closed 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);
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!
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.
Thanks for the explanation, I will explore this.
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:
For reference, here's the forum thread that started this suggestion.
Thanks!