Meteor.js:如何将一个帮助程序的数据上下文传递给另一个帮助程序



如果我有一个模板:

<template name="myTemplate">
  {{foo}}
</template>

和模板帮助程序:

Template.myTemplate.foo = function() {
   blah = Session.get('blah');
   // code to do stuff with blah
   return blah;
};

然后我有另一个模板:

<template name="myOtherTemplate">
   {{foo}}
</template>

并且我希望此模板的数据上下文与以前的模板相同,该怎么办?

我首先想到使用 {{#with}} 可能是正确的方法,但这似乎只有在第二个模板的范围已经在第一个模板内时才有效。

最终,我希望能够在另一个模板中使用为一个模板定义的所有帮助程序,并知道如何做到这一点。

似乎你在问以下两个问题之一:

  1. 如果您在 myTemplate 中使用 myOtherTemplate ,则其他模板的上下文将与此模板相同,除非您明确地将其作为部分的第二个参数传递给它。

    <template name="myTemplate">
      {{> myOtherTemplate foo}}
    </template>
    
  2. 如果要跨多个模板使用帮助程序,请在全局帮助程序中声明它。这将使{{foo}}在所有模板中可用:

    Handlebars.registerHelper("foo", function() {
       blah = Session.get('blah');
       // code to do stuff with blah
       return blah;
    });
    
  3. 如果要动态创建自己的数据上下文(这种情况很少见),请执行以下操作:

    <template name="myTemplate">
      {{{customRender}}}
    </template>
    Template.myTemplate.customRender = function() {
       return Template.otherTemplate({
           foo: something,
           bar: somethingElse,
           foobar: Template.myTemplate.foo // Pass in the helper with a different name
       });
    };
    

    这个对象基本上是 Iron-Router 在渲染时传递给你的模板的对象。请注意,您需要使用三重车把{{{ }}}或使用new Handlebars.SafeString告诉它不要转义模板。

相关内容

最新更新