【问题标题】:Iterating through an array with Spacebars使用空格键遍历数组
【发布时间】:2015-01-25 04:53:50
【问题描述】:

这是我的last question 的第二部分。感谢一些乐于助人的人,我现在有一个如下所示的文档:

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

具体来说,我想从空格键中 data 的每个属性中提取值并对其进行迭代以创建一个表 - 我知道对象 data 中的字段数,但数字可能会有所不同。是的,我知道这是asked before,但似乎没有人能够给出令人满意的有效答案。但作为最终结果,我想连续显示整个文档,像这样

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

提前感谢您的帮助。

【问题讨论】:

    标签: meteor spacebars


    【解决方案1】:

    这是完整的工作示例:

    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>
    

    【讨论】:

    • 请查看我更新的问题。问题是我不仅要显示data 对象,还要显示文档的其余部分。
    • 我用经过测试的解决方案更新了答案。那是你要找的吗?我不清楚每个文档是否具有相同的结构或字段数量是否不同。
    • data 中的字段数可以变化。这与显示文档的其余部分相结合,形成了一个结。
    • 好的 - 试试更新版本。编写 columns 帮助程序的方法有上百万种,但整体结构应该可以帮助您实现解决方案。
    • 谢谢!现在完美运行。我不知道你可以在辅助函数中引用this
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    相关资源
    最近更新 更多