如何打印流星模板中的键和值? [英] How to print key and values in Meteor Template?

查看:91
本文介绍了如何打印流星模板中的键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从帮手中获得JSON

  {
Name:abc,
年龄:24,
地址{
street:xyz street,
city:zyz city,
country:XY


$ / code $ / pre

我想用键和值打印地址

 < template name =User> 
{{#with user}}
姓名:{{姓名}}
年龄:{{年龄}}
{{#每个地址}}
{ key}}:{{value}} //这是我的问题
{{/ each}}
{{/ with}}

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

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



您可以重写Address helper,使其返回一个数组而不是一个对象。

 模板.User.helpers({
地址: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>


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?

解决方案

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>

这篇关于如何打印流星模板中的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆