Harry
Harry

Reputation: 55029

Meteor set overall template context

In meteor I can set various template helpers like this:

Template.story.title = function () {
  return "title";
};
<template name="story">
  <h3>{{title}}</h3>
  <p>{{description}}</p>
</template>

Which is great but, if I have a lot of variables I wouldn't want to set them individually, I want to pass the context to the main template.

How do I do that?

Template.story.data = function () {
  return {title:"title", description:"desc"};
};
<template name="story">
  <h3>{{title}}</h3>
  <p>{{description}}</p>
</template>

That doesn't work. THanks

Upvotes: 8

Views: 2197

Answers (2)

Tom Coleman
Tom Coleman

Reputation: 3037

You can set the context of the template when you call it:

{{> story data}}

Template.outerTemplate.data = function() { 
  return {title:"title", description:"desc"};
}

Or you can just use {{#with}} to set the the template context on the fly:

{{#with data}}
  {{title}}
{{/with}}

Upvotes: 12

matthias
matthias

Reputation: 2264

You are absolutely on the right way but missed to use your template variable the way you defined it. As Template.story.data is defined to return an object, you should use it like an object:

<template name="story">
  <h3>{{data.title}}</h3>
  <p>{{data.description}}</p>
</template>

Voilá. Of course every template variable can hold more than just a string.

Upvotes: 5

Related Questions