Can Meteor child templates access parent template helpers?

懵懂的女人 提交于 2019-12-03 15:41:26

问题


Say we have a parent template and a child template:

<template name="parent">
  {{> child }}
</template>

<template name="child">
  {{#if show}}
    //Do something
  {{/if}}
</template>

If we assign 'show' to the parent template:

if (Meteor.isClient){
   Template.parent.show = function(){
     return Session.get('isShowing');
   }
}

Is there any way for the child template to have access to it?


回答1:


Edit

You could make a universal handlebars helper so you could use Sessions values anywhere in your html:

Client js

Handlebars.registerHelper('session', function(key) {
    return Session.get(key);
});

Client HTML

<template name="child">
  {{#if session "show"}}
    //Do something
  {{/if}}
</template>

Similarly, you could also use {{session "show"}} / {{#if session "show"}} in your parent template and not have to use the Template.parent.show helper anymore.

Regarding the use of ../ notation. There are certain scenarios it may not work: https://github.com/meteor/meteor/issues/563. Basically it works within {{#block helpers}} but not with templates, but it would work in a block helper if it contains a subtemplate.

<template name="child">
    {{#if ../show}}
       Do something
    {{/if}}
</template>



回答2:


You can also register a common helper :

Template.registerHelper('isTrue', function(boolean) {
    return boolean == "true";
});

And call it just like that in your html:

<input type="checkbox" checked="{{isTrue attr}}"/>


来源:https://stackoverflow.com/questions/15127121/can-meteor-child-templates-access-parent-template-helpers

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