It is easy to iterate an array with Handlebars.js like:
{{#each comments}}
<div class="comment">
<h2>{{title}}</h2>
{{{{url}}}
</div>
{{/each}}
and an array like:
{
comments: [
{ url: "http://www.yehudakatz.com", title: "Katz Got Your Tongue" },
{ url: "http://www.sproutcore.com/block", title: "SproutCore Blog" },
]
}
But I don't find a method to iterate an object like:
{
headers: {
"Host": "www.example.com",
"Location": "http://www.example.com",
... Much more map items ...
}
}
Is there any method to iterate an object with Handlebars.js? Or do I have to restructure the object like:
{
headers: [
{ key: "Host", value: "www.example.com" },
{ key: "Location", value: "http://www.example.com" },
]
}
This is now supported with:
{{#each headers}}
Key: {{@key}}, Value: {{this}}
{{/each}}
The answer above is in the right track, this is my refinement:
Handlebars.registerHelper( 'eachInMap', function ( map, block ) {
var out = '';
Object.keys( map ).map(function( prop ) {
out += block.fn( {key: prop, value: map[ prop ]} );
});
return out;
} );
And to use it:
{{#eachInMap myMap}}
key:{{key}} value: {{value}}
{{/eachInMap}}
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