Meteor - Templates


Advertisements


Meteor templates are using three top level tags. The first two are head and body. These tags perform the same functions as in regular HTML. The third tag is template. This is the place, where we connect HTML to JavaScript.

Simple Template

Following example shows how this works. We are creating a template with name = "myParagraph" attribute. Our template tag is created below the body element, however, we need to include it before it is rendered on the screen. We can do it by using {{> myParagraph}} syntax. In our template, we are using double curly braces ({{text}}). This is meteor template language called Spacebars.

In our JavaScript file, we are setting Template.myParagraph.helpers({}) method that will be our connection to our template. We are only using text helper in this example.

meteorApp.html

<head>
   <title>meteorApp</title>
</head>
 
<body>
   <h1>Header</h1>
   {{> myParagraph}}
</body>
 
<template name = "myParagraph">
   <p>{{text}}</p>
</template>

meteorApp.js

if (Meteor.isClient) {
   
   // This code only runs on the client
   Template.myParagraph.helpers({
      text: 'This is paragraph...'
   });
}

After we save the changes, following will be the output −

Meteor Templates Output

Block Template

In the following example, we are using {{#each paragraphs}} to iterate over the paragraphs array and return template name = "paragraph" for each value.

meteorApp.html

<head>
   <title>meteorApp</title>
</head>
 
<body>
   <div>
      {{#each paragraphs}}
         {{> paragraph}}
      {{/each}}
   </div>
</body>
 
<template name = "paragraph">
   <p>{{text}}</p>
</template>

We need to create paragraphs helper. This will be an array with five text values.

meteorApp.js

if (Meteor.isClient) {
   
   // This code only runs on the client
   Template.body.helpers({
      paragraphs: [
         { text: "This is paragraph 1..." },
         { text: "This is paragraph 2..." },
         { text: "This is paragraph 3..." },
         { text: "This is paragraph 4..." },
         { text: "This is paragraph 5..." }
      ]
   });
}

Now, we can see five paragraphs on the screen.

Meteor Templates Output 2

Advertisements
E-Books Store