Meteor子模板可以访问父模板助手吗?

J2K*_*J2K 16 handlebars.js meteor

假设我们有父模板和子模板:

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

<template name="child">
  {{#if show}}
    //Do something
  {{/if}}
</template>
Run Code Online (Sandbox Code Playgroud)

如果我们将'show'分配给父模板:

if (Meteor.isClient){
   Template.parent.show = function(){
     return Session.get('isShowing');
   }
}
Run Code Online (Sandbox Code Playgroud)

子模板有没有办法访问它?

Aks*_*hat 8

编辑

你可以制作一个通用的把手助手,这样你就可以在你的html中的任何地方使用Sessions值:

客户js

Handlebars.registerHelper('session', function(key) {
    return Session.get(key);
});
Run Code Online (Sandbox Code Playgroud)

客户端HTML

<template name="child">
  {{#if session "show"}}
    //Do something
  {{/if}}
</template>
Run Code Online (Sandbox Code Playgroud)

同样,您也可以在父模板中使用{{session "show"}}/ {{#if session "show"}}而不必再使用Template.parent.show帮助程序.

关于../符号的使用.在某些情况下它可能不起作用:https://github.com/meteor/meteor/issues/563.基本上它可以在{{#block helpers}}中工作,但不能在模板中工作,但如果它包含子模板,它将在块帮助器中工作.

<template name="child">
    {{#if ../show}}
       Do something
    {{/if}}
</template>
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是,人们可以在车把中访问父上下文,但不能以编程方式访问辅助/上下文.你知道这是否改变了吗? (3认同)