How do we execute javascript in Handlebars template? For example I have the following
<script>
var config = {a: 1}
</script>
I want to be able to get the value of config.a
inside a Handlebars template.
You can do this by registering a helper method:
Handlebars.registerHelper("key_value", function (obj, fn) {
var soFar = "";
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
soFar += fn({key:key, value:obj[key]});
}
}
return soFar;
});
And then you can access the key/value pairs in the template.
<table>
{{#key_value someData}}
<tr>
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
{{/key_value}}
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With