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 a map like:
{
headers: {
"Host": "www.example.com",
"Location": "http://www.example.com",
... Much more map items ...
}
}
Is there any method to iterate a map with Handlebars.js? Or I have to restructurate the object like:
{
headers: [
{ key: "Host", value: "www.example.com" },
{ key: "Location", value: "http://www.example.com" },
]
}
Recent versions of Handlebars.js support a more readable iteration format (see here):
In my opinion this is less surprising than introducing the
@key
syntax as suggested by Tasos Zervos' answer.The answer above is in the right track, this is my refinement:
And to use it:
This is now supported with:
all you have to do is register a helper like so:
in your template you can call that:
that's it. Hope it is of any use
A more complete example for use with Map() - with supporting functions taken from handlebars - which will allow block vars inside the eachOfMap to work.
Usage:
In case someone landed to this question while googling for a way to iterate ES6
Map
in Handlebars, here is a helper:Example, demonstrating
Map
initialization and iteration:Use new helper in your Handlebars.js template:
Now you're all set to iterate over native ES6
Map
in Handlebars!