繁体   English   中英

在Blaze模板中访问对象的属性名称

[英]Access an object's property names in a Blaze template

说我有一个看起来像这样的帮手:

Template.profile.helpers({
  info: {
    Name: 'Bob Dinkleberg',
    Age: 45,
    Location: 'Earth, Milky Way'
  }
});

我想把这个信息放在<ul> 这是一些伪代码:

<template name="profile>
  <ul>
    {{#each}}
      <li> {{key}}: {{property}} </li>
    {{/each}}
  </ul>
</template>

请原谅我,如果这是微不足道的,我是Meteor和Blaze的新手,我无法在网上找到解决方案。

如果要按照请求循环访问对象属性和值,可以通过以下方式执行泛型:

Template.content.onCreated(function() {
  this.properties = new ReactiveVar({
    Name: 'Bob Dinkleberg',
    Age: 45,
    Location: 'Earth, Milky Way'
  });
});

Template.content.helpers({
  keys: function () {
    return Object.keys(Template.instance().properties.get());
  },
  key_value_pair: function() {
    return { key: this, value: Template.instance().properties.get()[this] };
  }
});

并使用此模板

<body>
  <h1>Property Loop</h1>
  <ul>
  {{> content}}
  </ul>
</body>

<template name="content">
  {{#each keys}}
    {{> property key_value_pair }}
  {{/each}}
</template>

<template name="property">
  <li>{{key}}: {{value}}</li>
</template>

我为你准备了这个MeteorPad,这是一个运行的例子:

http://meteorpad.com/pad/24MGwbuMNCcXCC7EW/PropertyLoop

干杯,汤姆

PS:如果永远不更改其值,则无需将对象创建为ReactiveVar。 但是当它作为ReactiveVar时,当对象内容发生变化时,表单会被重新更新。

这将有所帮助:

http://meteorcapture.com/spacebars/

您想使用{{#with}}

<template name="profile">
  <ul>
    {{#with info}}
      <li>{{Name}}</li>
      <li>{{Age}}</li>
      <li>{{Location}}</li>
    {{/with}}
  </ul>
</template>

你的帮助代码是正确的:

Template.profile.helpers({
  info: {
    Name: 'Bob Dinkleberg',
    Age: 45,
    Location: 'Earth, Milky Way'
  }
});

我个人喜欢养成将助手的名称映射到返回某个东西的函数的习惯。

Template.profile.helpers({

  info: function(){

    return {
      Name: 'Bob Dinkleberg',
      Age: 45,
      Location: 'Earth, Milky Way'
    };

  }

});

编辑

Template.content.helpers({

  info: function(){
    var obj = {
      Name: 'Bob Dinkleberg',
      Age: 45,
      Location: 'Earth, Milky Way'
    };
    var arrayOfObjects = [];

    // creating an array of objects
    for (key in obj){
      arrayOfObjects.push({key: key, value: obj[key]});
    };
    console.log("This is the array of objects: ", arrayOfObjects);
    return arrayOfObjects;
  },

});

HTML:

{{#each info}}
    {{value}}
{{/each}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM