【问题标题】:How iterate through two array in a object using Template helpers in Meteor.js如何使用 Meteor.js 中的模板帮助器遍历对象中的两个数组
【发布时间】:2015-02-24 21:12:41
【问题描述】:

我的 HTML 类似于这个

<template name="stop">  
   {{#each thumb}}

  <tr>
    <td class="image" ><img src="{{this.data}}"></td>
    <td>
     <center style="float:right; margin-bottom: 25%;">    
       <h2> Do you like this product? </h2>

       <h2>{{this.text}}</h2></center>
    </td>
  </tr>
  {{/each}}

</template>

这个模板是指我的模板助手,看起来像这样

Template.stop.helpers( {
        'thumb': function(data) {
            console.log(z);
            return tweetImages.findOne()
        })

tweetImage.findOne() 输出这个

Object {_id: "1", data: Array[7], text: Array[7]}

每次模板运行时,我都会尝试遍历两个数组中的每个项目,但每次都会输出每个数组的所有 7 个值。我知道这在某处需要上下文变量,但我无法解决。有人有什么想法吗?

【问题讨论】:

    标签: javascript json meteor handlebars.js this


    【解决方案1】:

    findOne 仅返回一个元素,因此您的 each 仅迭代一次。 您需要一个嵌套的 each 来通过 datatext 属性,如下所示:

    {{#each thumb}}
      ...
      {{#each data}}
        //but you won't be able to get 'text' here
      {{/each}}
      ...
    {{/each}}
    

    但正如您所见,您将无法使用此方法同时访问数据和文本数组。也许您可以修改助手返回的数据,使其具有以下形式:

    [
      {data: ..., text: ...},
      {data: ..., text: ...},
      {data: ..., text: ...},
      ...
    ]
    

    所以你可以这样做:

    {{#each thumb}}
      ...
      {{data}}
      {{text}}
      ...
    {{/each}}
    

    要重写您的数据,您可以使用 for 循环:

    Template.stop.helpers({
      'thumb': function() {            
        var result = tweetImages.findOne();
        var newResult = [];
        for(var i = 0; i < result.data.length; i++) {
          newResult[i] = {data:result.data[i], text:result.text[i]};
        }
        return newResult;
      }
    });
    

    【讨论】:

    • 在这种情况下,您知道如何重新编辑我的助手中返回的数据结构吗?
    • 我在答案中添加了它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2023-01-10
    • 2015-04-21
    • 2014-07-15
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多