How to print key and values in Meteor Template?

跟風遠走 提交于 2019-12-21 04:28:41

问题


I have JSON from helper

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

I want to print the address with key and values

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

How to print key and values in a template?


回答1:


The {{#each}} block helper only accepts cursors and arrays arguments.

You could override the Address helper to make it return an array instead of an object.

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

You might want to define this utility function as a template helper :

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>



回答2:


Changes to be made in JS

var AddressSet=CollectionName.find( {  } );

Changes to be made in HTML

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

       {{/each}}


来源:https://stackoverflow.com/questions/30234732/how-to-print-key-and-values-in-meteor-template

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