How to get the @index of nested #each in meteor
Asked Answered
B

1

8

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({
    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>
Boneyard answered 22/9, 2015 at 23:23 Comment(2)
just a suggestion: with ../you can get access to the parent context, so i'd try ../row @indexActor
@Actor - i couldn't figure out how to use your suggestion. should it be ../@index? if so, it didn't work out for me. Keith's answer below solved the problem. updating the main textBoneyard
P
17

You need to use let to capture the index, like:

{{#let rowIndex=@index}}
    {{#each cell in row}}
        <div class="cell {{cellState @index rowIndex}}">{{this}}</div>
    {{/each}}
{{/let}}
Progenitive answered 23/9, 2015 at 4:26 Comment(1)
@keith nicholas, that's exactly what I was looking for. problem solved.Boneyard

© 2022 - 2024 — McMap. All rights reserved.