流星和把手#each迭代对象

Har*_*rry 21 javascript handlebars.js meteor

我想使用#each带有不是数组的对象的把手.

我怎么做?我需要它仍然可以使用meteor的特殊功能#each.

我的目标是:

{
  john: "hello",
  bob: "hi there"
}
Run Code Online (Sandbox Code Playgroud)

我想要得到这样的输出:

<div>hello</div>
<div>hi there</div>
Run Code Online (Sandbox Code Playgroud)

Aks*_*hat 37

您需要在js中使用帮助器来帮助把手理解您的对象:

添加到您的客户端js

Template.registerHelper('arrayify',function(obj){
    var result = [];
    for (var key in obj) result.push({name:key,value:obj[key]});
    return result;
});
Run Code Online (Sandbox Code Playgroud)

{{name}}在你的html中使用(你也可以使用键):

{{#each arrayify myobject}}
   <div title="hover here {{name}}">{{value}}</div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)

myobject 来自您的模板:

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


小智 8

您可以使用下划线_.map将对象转换为数组

HTML:

<template name="test">
    {{#each person}}
       <div>{{greeting}}</div>
    {{/each}}
</template>
Run Code Online (Sandbox Code Playgroud)

JS:

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