0

Within myjavascript.js, I have an array like so:

games = [{name: "football"},{name:"basketball"}];

Within my games.handlebars I have included my javascript file at the top of the page as normal. I want to formulate a table like so:

{{#if games}}
  {{#each games}}
    <tr>{{name}}</tr>
  {{/each}}
{{#else}}
  <h1> No games </h1>
{{/if}}

I always seem to hit the else statement, it thinks games is empty. In the java-script console in my browser I can type games and it shows the object, i can see all the data in it.

What is it that I am doing wrong?

Toby
  • 517
  • 1
  • 5
  • 15
  • Not directly related to your problem, but idiomatic Handlebars would be to skip the `{{#if}}` statement, and simply do `{{#each games}}` with an `{{else}}` before the `{{/each}}`. The `{{else}}` will be executed if `games` is null or empty. –  Dec 04 '14 at 14:13
  • Merely defining `games` in some nearby JS, or in a ` –  Dec 04 '14 at 14:15

2 Answers2

0

You're not ending your each statement, also each iteration in the loop references to this. You should also use games.length instead of just games to check if the array contains values.

{{#if games.length}}
  {{#each games}}
    <tr>{{this.name}}</tr>
  {{/each}}
{{else}}
  <h1> No games </h1>
{{/if}}

each also has an else, which shows if the array is empty.

{{#each games}}
  <tr>{{this.name}}</tr>
{{else}}
  <h1> No games </h1>
{{/each}}
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
0

Thank you for your help.

The problem was actually quite interesting. I'm using Handlebars through NodeJS and Express. NodeJS is installed and imported through node server side as well as in my front end pages by including the handlebars js file.

This caused an interesting conflict, When I was pulling in the handlebars template from my pages from front end java script, the back end was actually evaluation the handlebars {{}} bracket statements first. As my values didn't exist at that point, it was returning HTML that did not include my handlebars {{}} brackets. This then meant the front end java script had nothing to evaluate.

The way I got around this was from this stackoverflow post. Basically I had to escape the handlebars brackets like this: \ {{}}. This then stopped server side from evaluating them before they are passed to the client side.

Community
  • 1
  • 1
Toby
  • 517
  • 1
  • 5
  • 15