是否有任何方法用Handlebars.js迭代地图? [英] Is there any method to iterate a map with Handlebars.js?
本文介绍了是否有任何方法用Handlebars.js迭代地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{{#each comments}} $ b $使用Handlebars.js迭代数组很容易b< div class =comment>
< h2> {{title}}< / h2>
{{{{url}}}
< / div>
{{/ each}}
以及一个数组:
{
评论:[
{url:http://www.yehudakatz.com,标题:Katz Got你的舌头},
{url:http://www.sproutcore.com/block,标题:SproutCore博客},
]
}
但我没有找到迭代地图的方法,如:
{
标题:{
主机:www.example.com,
位置:http:// www。 example.com,
...更多地图项目...
}
}
是否有任何方法用Handlebars.js迭代地图?或者我必须重新构造这样的对象:
{
headers:[
{key:Host ,value:www.example.com},
{key:Location,value:http://www.example.com},
]
}
解决方案
上面的答案在正确的轨道上,这是我的细化:
Handlebars.registerHelper('eachInMap',function(map,block){
var out ='' ;
Object.keys(map).map(function(prop){
out + = block.fn({key:prop,value:map [prop]});
}) ;
退货;
});
使用它:
{{#eachInMap myMap}}
key:{{key}} value:{{value}}
{{/ eachInMap}}
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" },
]
}
解决方案
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}}
这篇关于是否有任何方法用Handlebars.js迭代地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文