如何在Meteor Template中打印键和值?

Ram*_*san 7 javascript handlebars.js meteor meteor-helper

我有助手的JSON

{
    "Name": "abc",
    "Age": 24,
    "Address" {
        "street" : "xyz street",
        "city" : "zyz city",
        "country" : "XY"
        }
}
Run Code Online (Sandbox Code Playgroud)

我想用键和值打印地址

<template name="User">
{{#with user}}
 Name : {{Name}}
 Age : {{Age}}
    {{#each Address}}
       {{key}} : {{value}} //Here is my question
    {{/each}}
{{/with}}
</template>
Run Code Online (Sandbox Code Playgroud)

如何在模板中打印键和值?

sai*_*unt 7

所述{{#each}}块助手仅接受光标和阵列参数.

您可以覆盖Address帮助程序,使其返回数组而不是对象.

Template.User.helpers({
  Address: function(){
    return _.map(this.Address, function(value, key){
      return {
        key: key,
        value: value
      };
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

您可能希望将此实用程序函数定义为模板帮助程序:

JS

Template.registerHelper("objectToPairs",function(object){
  return _.map(object, function(value, key) {
    return {
      key: key,
      value: value
    };
  });
});
Run Code Online (Sandbox Code Playgroud)

HTML

<template name="User">
  <ul>
    {{#each objectToPairs Address}}
      <li>{{key}} - {{value}}</li>
    {{/each}}
  </ul>
</template>
Run Code Online (Sandbox Code Playgroud)