Access to Parent Assistant in Meteor

I often find that I am sharing my work with templates that the same helpers can still use.

So, let's 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 him call it dataHelper :

 Template.MainTemplate.helpers({ dataHelper: function() { //do some stuff return result } }) 

Unfortunately, this helper cannot be accessed in the first through fourth template, simply by typing {{dataHelper}} , how the events work.

My solution was to create a global helper, but that seems a bit 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.

Did I miss something simple here?

+5
source share
3 answers

There is no obvious way to do this in the current version of the meteor. One solution is to inherit helpers from the parent for the child template. You can do this quite easily using meteor-template-extension . Here is an example:

HTML

 <body> {{> parent}} </body> <template name="parent"> <h1>parent</h1> {{> child}} </template> <template name="child"> <h2>child</h2> <p>{{saySomething}}</p> </template> 

Js

 Template.parent.helpers({ saySomething: function() { return Random.choice(['hello', 'dude!', 'i know right?']); } }); Template.child.inheritsHelpersFrom('parent'); 

The child template inherits all of its parent helpers, so it has direct access to saySomething .

This method has two drawbacks:

  • you need to specify the relation inheritsHelpersFrom
  • all parent assistants are inherited
+5
source

You can access the parent helpers using either a two-dot type notation like {{yourParentHelper ..}} . Look here for more information (end of article)

You can also access the parent data context in javascript:

 var parent_data = Template.parentData(); 

By the way, you can add a parameter to reach the third parent, for example:

 var parent_data = Template.parentData(3); 
+5
source

Two-point notation seems to work best in {{#each}} , and I'm not sure about the actual patterns. One option is to use {{#with}} , although this limits you mainly to one helper. eg:.

 <template name="parent"> {{#with dataHelper}} {{> first}} {{> second}} {{/with}} </template> 

This will set the data context of the dataHelper child helpers, and you can access it from {{this}} inside the template. I suppose you could make a dataHelper object and then pass several pieces of data this way.

+2
source

All Articles