【问题标题】:How to print key and values in Meteor Template?如何在 Meteor 模板中打印键和值?
【发布时间】:2015-07-25 21:59:01
【问题描述】:

我有来自助手的 JSON

{
    "Name": "abc",
    "Age": 24,
    "Address" {
        "street" : "xyz street",
        "city" : "zyz city",
        "country" : "XY"
        }
}

我想用键和值打印地址

<template name="User">
{{#with user}}
 Name : {{Name}}
 Age : {{Age}}
    {{#each Address}}
       {{key}} : {{value}} //Here is my question
    {{/each}}
{{/with}}
</template>

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

【问题讨论】:

    标签: javascript meteor handlebars.js meteor-helper


    【解决方案1】:

    要在 JS 中进行的更改

    var AddressSet=CollectionName.find( {  } );
    

    在 HTML 中进行的更改

          {{#each AddressSet}}
            {{#each Address}}
                  {{this.street}}
                  {{this.city}}
                  {{this.country}}
           {{/each}}
    
           {{/each}}
    

    【讨论】:

    • 我想打印键和值。您的代码只有值。不管怎样,谢谢。 @saimeunt 正确理解我的问题。
    • 它没有回答问题,密钥应该是未知的。
    【解决方案2】:

    {{#each}} 块助手只接受游标和数组参数。

    您可以覆盖地址帮助器,使其返回数组而不是对象。

    Template.User.helpers({
      Address: function(){
        return _.map(this.Address, function(value, key){
          return {
            key: key,
            value: value
          };
        });
      }
    });
    

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

    JS

    Template.registerHelper("objectToPairs",function(object){
      return _.map(object, function(value, key) {
        return {
          key: key,
          value: value
        };
      });
    });
    

    HTML

    <template name="User">
      <ul>
        {{#each objectToPairs Address}}
          <li>{{key}} - {{value}}</li>
        {{/each}}
      </ul>
    </template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2016-07-01
      相关资源
      最近更新 更多