Reputation: 5638
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.
Upvotes: 10
Views: 10408
Reputation: 8417
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>
Upvotes: 14