How to print key and values in Meteor Template?
Asked Answered
A

2

7

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?

Arboreous answered 14/5, 2015 at 10:15 Comment(0)
B
7

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>
Bayle answered 14/5, 2015 at 10:48 Comment(0)
I
1

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}}
Incorporeal answered 14/5, 2015 at 11:39 Comment(2)
I want to print key and as well as value. Your code has only values. Anyway thanks. @Bayle Understand my question right.Arboreous
It doesn't answer the question, the keys are supposed to be unknown.Baptistery

© 2022 - 2024 — McMap. All rights reserved.