Meteor and handlebars #each to iterate over object

◇◆丶佛笑我妖孽 提交于 2019-11-30 06:37:06

问题


I want to use handlebars #each with an object that's not an array.

How do I do that? I need it to still work with meteor's special features with #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>

回答1:


You need to use a helper in your js to help handlebars understand your object:

Add to your client 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:

{{#each arrayify myobject}}
   <div title="hover here {{name}}">{{value}}</div>
{{/each}}

myobject comes from your template:

Template.templatename.helpers({
    myobject : function() { 
      return { john:"hello", bob: "hi there" } 
    }
});



回答2:


You can convert your object into array with underscore _.map

html:

<template name="test">
    {{#each person}}
       <div>{{greeting}}</div>
    {{/each}}
</template>

js:

Template.test.helpers({
    person : function () { 
        return _.map(object, function(val,key){return {name: key, greeting: val}});
    }
});



回答3:


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:

UI.registerHelper("arrayify", function(obj){
    result = [];
    for (var key in obj){
        result.push({name:key,value:obj[key]});
    }
    return result;
});


来源:https://stackoverflow.com/questions/15035363/meteor-and-handlebars-each-to-iterate-over-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!