(SOLVED) How to get the @index of nested #each in meteor


#1

I am trying and failing to figure out the solution for this: I have a 10x10 array representing 10 rows with 10 cells each. I want to draw a grid and set each cell’s background-color according to the value in the array: a 0 value will be white and a 1 value will be black

i’ve set up this css:

.cell{
  height: 20px;
  width: 20px;
  float: left;
  margin: 0;
  padding: 0;
}

.cell.live{
  background-color: black;
}

.cell.dead {
  background-color: white;
}

I created a helper that will return ‘live’ or ‘dead’ according to the value in the array according to 2 arguments: x and y

here’s the code:

Template.grid.helpers({
    rows: function() {
      return Session.get('screen'); //the 10x10 array
     },
    cellState: function(x, y) {
      if(screenArray[x][y] === 1){
        return 'live';
      }
      else {
        return 'dead';
      }
    }
  });

my problem is that i don’t know how to get the @index of both of my #each loops

here’s my template, i couldn’t find a solution for the ???

<template name="grid">
  <div class="gridWrapper">
  {{#each row in rows}}
    <div class="row">
      {{#each cell in row}}
        <div class="cell {{cellState @index ?????}}">{{this}}</div>
      {{/each}}
    </div>
  {{/each}}
</div>
</template>

here’s the solution, I simply use the #let block to capture the @index of the outer (rows) iterator and then pass it along with the @index of the inner iterator to my function.
here’s the updated working template.

<template name="grid">
  <div class="gridWrapper">
  {{#each row in rows}}
    <div class="row">
      {{#let rowIndex=@index}}
      {{#each cell in row}}
        <div class="cell {{cellState rowIndex @index}}">{{this}}</div>
      {{/each}}
      {{/let}}
    </div>
  {{/each}}
</div>
</template>

#2

Simplify it.

Template.grid.helpers({
    cellState: function() {
      if(this){
        return 'live';
      }
      else {
        return 'dead';
      }
    }
  });

<template name="grid">
  <div class="gridWrapper">
  {{#each row in rows}}
    <div class="row">
      {{#each cell in row}}
        <div class="cell {{cellState}}">{{this}}</div>
      {{/each}}
    </div>
  {{/each}}
</div>
</template>

You also have a rows helper for your grid template to provide the data context right?


#3

I just edited the post and added the rows helper which simply returns the Array.
the solution you wrote above doesn’t address the issue since the dead/live must be decided according to 2 arguments.
I still need a way to pass the @index of both of the #each blocks to the cellState helper.