0

I'm trying to build a simple memory card game in Meteor and I can't seem to create a grid of my cards to populate in html. I'm just trying to get a 4x4 grid for right now.

Here is the javascript:

Template.body.helpers({
    cards: function() {
      var allCards = Deck.find({}).fetch();
      var chunks = [];

      while (allCards.length > 0) {
        chunks.push(allCards.slice(0, 4));
        allCards = allCards.slice(4);
      }

      return chunks;
    },
  });

And here is the HTML:

<body>
  <div class="container">

    <div name="gameBoard">
      {{#each cards}}
        {{> cardsRow}}
      {{/each}}
    </div>

  </div>
</body>

<template name="cardsRow">
  <div class="row">
    {{#each row}}
      {{> card}}
    {{/each}}
  </div>
</template>

<template name="card">
  <span class="text">{{text}}</span>
</template>

Right now I just have simple text entries in the db to see what I'm doing before I pull in images. I've tried console logging from my JS and I believe I'm creating the array of spliced rows correctly so I think the problem may be in the way I have arranged the markdown.

I tried pulling the each cards loop into a template as well instead of inside the body but I'm not sure how to render templates on demand. This is potentially an option since I have a new game button event listener that could call a render. I'm just not sure how to explicitly render in Meteor.

I tried following this previous post but I couldn't get it to work: How do I populate a bootstrap grid system using handlebars for each command in Meteor.js?

Thoughts? I can provide more of my code base if needed.

Community
  • 1
  • 1

1 Answers1

0

Neither row in {{#each row}} in the "cardsRow" template, nor {{text}} in the "cards" template, refer the way that you hope they do. You need to define row and text as template helpers for each of these templates. In a template helper, this refers to the data object associated with the template.

In your case, when you iterate through #each cards in "container", this is passed into the "cardsRow" template as one of the chunks defined in your cards helper function. The helpers below should illustrate this, and are sufficient for your example.

Template.cardsRow.helpers({
    row: function() {
        console.log(this); // a chunk of cards
        return this;
    }
});

Template.card.helpers({
    text: function() {
        console.log(this); // a number in a chunk
        return this;
    }
});
pfkurtz
  • 494
  • 3
  • 7
  • With such a simple example, you could refer to `this` directly in your template, just FYI: `{{this}}` – pfkurtz Feb 24 '15 at 00:06
  • Thanks! I got it working now. Yeah I think I was confusing the {{text}} inside the html file as referencing the database but really its what is returned from the helper method in the js file. I just called this.text in the return and I can see my sample characters. – Jordan Schreuder Feb 24 '15 at 01:56