从 Meteor 中的助手访问原始的 TemplateInstace

Access an original TemplateInstace from the helper in Meteor

谁能告诉我如何从 meteor helper 访问 original TemplateInstance。我知道 Template.instance() 但它似乎 return 调用助手 的模板实例 ,而不是助手 [=] 的模板实例28=]已定义.

假设我们有两个小模板:

<template name='demo'>
  <h1>{{helper}}</h1>
  {{# border}}
    <h2>{{helper}}</h2>
  {{/border}}
</template>

<template name='border'>
  <div style="border:1px solid red">
    {{> UI.contentBlock}}
  </div>
</template>

具有以下行为:

Template.demo.created = function() {
  this.result = "OK";
}

Template.demo.helpers({
  helper: function() {
    var tmpl = Template.instance();
    return tmpl.result || "FAILED";
  }
});

我希望为 demo 模板获得两个 "OK":第二个应该在红色边框中。但是由于 Template.instance() return 的原始 TemplateInstance 仅当在其所有者模板的顶层调用 helper 时,结果才为 "FAILED"(当然在红色边框中) .

问题:有没有publicapi得到原文TemplateInstance(无需遍历 view/parentView/_templateInstace)?

我认为你的主要问题是你没有正确设置模板实例变量。试试下面的代码...

设置一个实例变量:

Template.instance().result.set("OK");

获取实例变量:

Template.instance().get("result");

因此您的更新代码将是:

Template.demo.created = function() {
    Template.instance().result.set("OK");
}

Template.demo.helpers({
    helper: function() {
        return Template.instance().get("result") || "FAILED";
    }
});

我认为最好的方法可能是设置会话变量,或使用反应变量(使用反应变量包 - here is the documentation)。

我制作了一个流星垫来展示更多 - here

基本上:

Template.demo.created = function() {
    result = new ReactiveVar('OK');
}

Template.demo.helpers({
    helper: function() {
        return result.get() || "FAILED";
    }
});

它似乎是已知的并且已经修复了 (?) Meteor 错误。更多信息:https://github.com/meteor/meteor/issues/3745

rclai 对 GitHub 的评论:

This was already addressed and fixed for the next release.

Run meteor like this, not sure if it still works: meteor --release TEMPLATE-CURRENT-DATA@0.0.1

Another alternative is to use aldeed:template-extensions, which has super nice features, especially with dealing with template instances and I believe their way of fetching the template instance is a workaround this issue.