Template.body vs Template.myTemplate

I am currently going through the Meteor tutorial ( https://www.meteor.com/try ) and came across something about templates that puzzles me.

The tutorial creates a simple Todo List application. In this application, the following HTML is placed in the simple-todos.html file :

<!-- simple-todos.html -->
<head>
  <title>Todo List</title>
</head>

<body>
  <div class="container">
    <header>
      <h1>Todo List</h1>
    </header>

    <ul>
      {{#each tasks}}
        {{> task}}
      {{/each}}
    </ul>
  </div>
</body>

<template name="task">
  <li>{{text}}</li>
</template>

      

Then the following JavaScript is placed in the simple-todos.js file :

// simple-todos.js
Tasks = new Mongo.Collection("tasks");

if (Meteor.isClient) {
  // This code only runs on the client
  Template.body.helpers({
    tasks: function () {
      return Tasks.find({});
    }
  });
}

      

At this point, the example works exactly as intended. However, when I try to find the documentation and also look at other examples on the internet, I noticed a slightly different syntax: Template.myTemplate instead of Template.body .

So, out of curiosity, I modified my JavaScript file to read:

Template.task.helpers({ ...

      

instead:

Template.body.helpers({ ...

      

However, when I run the application now, the client is not displaying data from the collection. I don't get errors on undefined types, for example if I am wrong about the template name in JavaScript, so it seems like it resolves the template correctly. But why is it not being used or displayed?

And go a little further: When is it appropriate to use Template.myTemplate and when is it appropriate to use Template.body?

+3


source to share


2 answers


Helper code only works for the attached template.

So, the code that works for Template.task

is only applicable to templates named "task".

Template.body is like the one-off that exists because it would be weird if it doesn't. This is a way to specifically target it <body>

, although there is technically no template named body.

So what's going on:

  • Parent template = body
  • Child pattern = task


Your logic says:

In the parent template, for each task found, render an instance of the child task template.

If you change your helper from body

to task

, you won't get any output at all unless you emulate a pattern that's already happening:

    <template name="task">
      {{#each tasks}}
       do something
      {{/each}}
    </template>

      

+7


source


This is because it <body>

is the parent template and you should treat it as such:

<template="body>stuff that normally goes in an HTML body here</template>



When you remove body helpers then no data is displayed at all because the helpers are passing data to the template. And without a helper for the template, that is, the body, you don't get any data.

0


source







All Articles