Helpers

So in our foosball app we are going to make it so you can create teams and then games involving two teams:

A simple model of our data\label

Create a new template in your views directory. This template is called teams. Note that while we call our file teams.html, Meteor actually doesn't really care about what you name it - it cares about the name attribute in the <template> element.

/client/views/teams.html

<template name="teams">
  <h3>Teams</h3>
</template>

Now use the spacebars render helper to get the teams template on the page:

/client/main.html

<head>
  <title>Foosboom</title>
</head>

<body>
  <h1>Foosboom</h1>

  {{> teams}}
</body>

First template rendered\label

Now we need an array of teams to render on the page. Later we'll make it so you can create your own teams, but for now we'll create some dummy teams.

In a template you can use spacebars to render data. Anything inside parentheses - {{ here! }} - is called a helper, and helpers can be defined to return data in our Javascript.

But which js file should we put it in? The convention is to create a Javascript file with the same name as the html file. Our html file is called "teams", so we'll create it's corresponding Javascript file "teams.js". Just put it in the same folder:

client/views/teams.js

Template.teams.helpers({

});

The helpers function takes an object as a parameter as you can see. Each key in the object will be what you can call in the template. So if you pass the object {title: 'Teams'}, you can now go {{ title }} in the template and it will evaluate to 'Teams'.

How helpers work\label

We actually want to do something a little more advanced - we want to make a helper return an array of teams.

client/views/teams.js

Template.teams.helpers({
  teams: [
    {name: "Team 1"},
    {name: "Team 2"},
  ]
});

Now in our template we can loop over arrays with Spacebars like this:

client/views/teams.html

<template name="teams">
  <h3>Teams</h3>
  <ul>
    {{#each teams}}
      <li>{{name}}</li>
    {{/each}}
  </ul>
</template>

Our data is rendered\label

Notice that inside of the #each block we go {{name}}, even though we have no name helper defined. This is because the data context changes inside the #each block. We loop through each item in the teams array, and since each item has a "name" attribute Meteor will automatically create a {{ name }} helper.

A new data context (the blue inside the each block) can open up additional helpers\label

Later we'll learn how you can provide a template with a data object, allowing Meteor to give us access to the data via helpers. If you're hungry right now for more information on data context, check out this article.