Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any method to iterate a map with Handlebars.js?

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" }, 
  ]
}
like image 444
Ferran Basora Avatar asked Mar 23 '12 12:03

Ferran Basora


2 Answers

This is now supported with:

{{#each headers}}
    Key: {{@key}}, Value: {{this}}
{{/each}}
like image 108
Tasos Zervos Avatar answered Sep 24 '22 22:09

Tasos Zervos


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}}
like image 37
unify Avatar answered Sep 23 '22 22:09

unify