2015-05-14 15 views
7

Ho JSON da aiutanteCome stampare chiave e valori in Meteor Template?

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

voglio stampare l'indirizzo con chiave e valori

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

Come stampare chiave e valori in un modello?

risposta

6

L'helper di blocco {{#each}} accetta solo argomenti di cursori e array.

È possibile sovrascrivere l'helper Indirizzo per fare in modo che restituisca una matrice anziché un oggetto.

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

Si potrebbe voler definire questa funzione di utilità come modello aiutante:

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> 
1

modifiche da apportare in JS

var AddressSet=CollectionName.find({ }); 

modifiche da apportare in HTML

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

     {{/each}} 
+0

voglio stampare chiave e così come il valore. Il tuo codice ha solo valori. Comunque grazie. @saimeunt Comprendere la mia domanda giusta. –

+0

Non risponde alla domanda, i tasti dovrebbero essere sconosciuti. –

Problemi correlati