I often find myself dividing my work into templates that still could use the same helpers.
So, say I have this template structure:
<template name="MainTemplate">
<div>{{> FirstTemplate}}</div>
<div>{{> SecondTemplate}}</div>
<div>{{> ThirdTemplate}}</div>
<div>{{> FourthTemplate}}</div>
</template>
Now each of these templates wants to use the same helper, let's call it dataHelper
:
Template.MainTemplate.helpers({
dataHelper: function() {
//do some stuff
return result
}
})
Sadly, this helper can't be accessed in template first through fourth by simply typing {{dataHelper}}
like how events work.
My solution has been to create a global helper instead, but that seems a tad overkill, especially since I have a few pages that don't care about these helpers at all. Another solution is to create four separate helpers but, hey, DRY.
Am I missing something simple here?
There isn't an obvious way to do this in the current version of meteor. One solution is for the child template to "inherit" the helpers from the parent. You can do this pretty easily using meteor-template-extension. Here's an example:
<body>
{{> parent}}
</body>
<template name="parent">
<h1>parent</h1>
{{> child}}
</template>
<template name="child">
<h2>child</h2>
<p>{{saySomething}}</p>
</template>
Template.parent.helpers({
saySomething: function() {
return Random.choice(['hello', 'dude!', 'i know right?']);
}
});
Template.child.inheritsHelpersFrom('parent');
The template child
inherits all of its parent's helpers so it has direct access to saySomething
.
This technique has two drawbacks:
inheritsHelpersFrom
relationshipYou can access your parent helpers using either a notation like {{yourParentHelper ..}}
with two dots. Have a look here for more informations (end of the article)
You can also access parent data context in javascript like that:
var parent_data = Template.parentData();
By the way, you can add a parameter to reach the third parent, for instance:
var parent_data = Template.parentData(3);
The double dot notation seems to work best within {{#each}}
loops, and I'm not having any luck within actual child templates. One option would be to use {{#with}}
, although that limits you to basically one helper. e.g.:
<template name="parent">
{{#with dataHelper}}
{{> first}}
{{> second}}
{{/with}}
</template>
This will set the data context of the child helpers to dataHelper
, and you can access them with {{this}}
inside the template. I suppose you could make dataHelper
an object and then pass in multiple pieces of data that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With