Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - Meteor and handlebars #each to iterate over object

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" } 
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...