使用Spacebars迭代数组

时间:2014-11-26 18:21:58

标签: meteor spacebars

这有点属于last question的第2部分。感谢一些乐于助人的人,我现在有一个如下文档:

{ "_id" : "dndsZhRgbPK24n5LD", "createdAt" : ISODate("2014-11-26T16:28:02.655Z"), "data" : { "cat1" : 493.6, "cat2" : 740.4 }, "owner" : "GiWCb8jXbPfzyc5ZF", "text" : "asdf" }

具体来说,我想从Spacebars中的data的每个属性中提取值并迭代它以创建一个表 - 我知道对象data中的字段数,但数量可能会有所不同。是的,我知道这已经asked before但似乎没有人能够给出一个有效的答案。但作为最终结果,我想连续显示整个文档,比如

<tbody>
  <tr>
    <td>493.6</td>
    <td>740.4</td>
    <td>asdf</td>
</tbody>

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

以下是完整的工作示例:

Cats = new Mongo.Collection(null);

Meteor.startup(function() {
  Cats.insert({
    data: {
      cat1: 100,
      cat2: 200
    },
    text: 'cat1'
  });

  Cats.insert({
    data: {
      cat1: 300,
      cat2: 400,
      cat3: 500
    },
    text: 'cat2'
  });
});

Template.cats.helpers({
  cats: function() {
    return Cats.find();
  },

  // Returns an array containg numbers from a cat's data values AND the cat's
  // text. For example if the current cat (this) was:
  // {text: 'meow', data: {cat1: 100, cat2: 300}}, columns should return:
  // [100, 200, 'meow'].
  columns: function() {
    // The current context (this) is a cat document. First we'll extract an
    // array of numbers from this.data using underscore's values function:
    var result = _.values(this.data);

    // result should now look like [100, 200] (using the example above). Next we
    // will append this.text to the end of the result:
    result.push(this.text);

    // Return the result - it shold now look like: [100, 200, 'meow'].
    return result;
  }
});
<body>
  {{> cats}}
</body>

<template name='cats'>
  <table>
    {{#each cats}}
      <tr>
        {{#each columns}}
          <td>{{this}}</td>
        {{/each}}
      </tr>
    {{/each}}
  </table>
</template>
相关问题