Sometimes, we want to call JavaScript function from Handlebars.
In this article, we’ll look at how to call JavaScript function from Handlebars.
How to call JavaScript function from Handlebars?
To call JavaScript function from Handlebars, we can register a helper.
For instance, we write:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<script id="some-template" type="text/x-handlebars-template">
{{printItems items}}
</script>
<div>
</div>
to add a template that uses the printItems
helper.
Then we create the printItems
helper and use it by writing:
Handlebars.registerHelper("printItems", (items) => {
return items.join(', ');
});
const source = $("#some-template").html();
const template = Handlebars.compile(source);
const data = {
items: ['foo', 'bar']
}
$('div').append(template(data));
We call Handlebars.registerHelper
method with the helper name and the helper function.
It accepts the value after the helper as the argument.
We have items
in data
, so the values in items
will be printed.
We return a string with the items
entries joined together into a string.
Then we get the template and render it with:
const source = $("#some-template").html();
const template = Handlebars.compile(source);
const data = {
items: ['foo', 'bar']
}
$('div').append(template(data));
Therefore, we see ‘foo, bar’ printed.
Conclusion
To call JavaScript function from Handlebars, we can register a helper.