javascript Meteor 和 handlebars #each 迭代对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15035363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Meteor and handlebars #each to iterate over object
提问by Harry
I want to use handlebars #each
with an object that's not an array.
我想将把手#each
与不是数组的对象一起使用。
How do I do that? I need it to still work with meteor's special features with #each
.
我怎么做?我需要它仍然与流星的特殊功能一起使用#each
。
My object is in the form of:
我的对象是以下形式:
{
john: "hello",
bob: "hi there"
}
I'm trying to get an output like this:
我试图得到这样的输出:
<div>hello</div>
<div>hi there</div>
回答by Akshat
You need to use a helper in your js to help handlebars understand your object:
你需要在你的 js 中使用一个 helper 来帮助把手理解你的对象:
Add to your client js
添加到您的客户端js
Template.registerHelper('arrayify',function(obj){
var result = [];
for (var key in obj) result.push({name:key,value:obj[key]});
return result;
});
And use (you can also use the key with {{name}}
) in your html:
并{{name}}
在您的 html 中使用(您也可以使用带有 的键):
{{#each arrayify myobject}}
<div title="hover here {{name}}">{{value}}</div>
{{/each}}
myobject
comes from your template:
myobject
来自您的模板:
Template.templatename.helpers({
myobject : function() {
return { john:"hello", bob: "hi there" }
}
});
回答by solo999
You can convert your object into array with underscore _.map
您可以使用下划线 _.map 将对象转换为数组
html:
html:
<template name="test">
{{#each person}}
<div>{{greeting}}</div>
{{/each}}
</template>
js:
js:
Template.test.helpers({
person : function () {
return _.map(object, function(val,key){return {name: key, greeting: val}});
}
});
回答by Robert Fines
It should be noted for people finding this now that the correct way to declare Handlebars helpers in Meteor as of this writing is with the UI.registerHelper method as opposed to Handlebars.registerHelper. So the above helper should look like this now:
现在发现这一点的人应该注意,在撰写本文时,在 Meteor 中声明 Handlebars 助手的正确方法是使用 UI.registerHelper 方法,而不是 Handlebars.registerHelper。所以上面的助手现在应该是这样的:
UI.registerHelper("arrayify", function(obj){
result = [];
for (var key in obj){
result.push({name:key,value:obj[key]});
}
return result;
});