Accessing parent helper in Meteor

醉酒当歌 提交于 2019-12-22 05:29:31

问题


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?


回答1:


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:

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 template child inherits all of its parent's helpers so it has direct access to saySomething.

This technique has two drawbacks:

  • you have to specify the inheritsHelpersFrom relationship
  • all of the parent's helpers are inherited



回答2:


You 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);



回答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.



来源:https://stackoverflow.com/questions/30922695/accessing-parent-helper-in-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!