jsdiaries-gd
jsdiaries-gd

Reputation: 169

How iterate through two array in a object using Template helpers in Meteor.js

My HTML resembles this

<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>

And this template refers to my template helper which look like this

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

tweetImage.findOne() outputs this

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

I'm trying to iterate through each item in both of the arrays for each time the template run but instead all the 7 values for each array get outputted each time. I know the contextual variable this is need somewhere but I cannot work it out. Would anyone have any ideas?

Upvotes: 1

Views: 1547

Answers (1)

255kb - Mockoon
255kb - Mockoon

Reputation: 6974

findOne returns only one element so your each only iterates one time. You need a nested each to go through the data or text property like this:

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

But as you can see you won't be able to access both data and text arrays with this method. Maybe you could modify the data returned by your helper so it has the following form:

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

So you could do:

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

To rewrite your data you could use a for loop:

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;
  }
});

Upvotes: 2

Related Questions