Iterating through an array with Spacebars

你。 提交于 2019-12-05 19:49:59

Here's complete working example:

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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!