是否可以访问使用Blaze.render()加载的模板的父数据上下文?

时间:2015-09-01 12:41:09

标签: javascript meteor meteor-blaze spacebars

我使用Blaze.render()Blaze.renderWithData()

在启动箱中加载模板
Blaze.renderWithData(Template.myTemplate, 
                     {"arg1":false, "arg2":"blabla"}, 
                     $("#dialogAnchor")[0]);

虽然通常可以在加载了空格键的模板中使用Template.parentData()直接访问父数据上下文(例如{{> myTemplate}}),但使用Blaze.render()时不可能这样做或Blaze.renderWithData()

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

我现在熟悉这个问题,因为没有人回答,这就是我如何处理它:

首先,使用Blaze.render()Blaze.renderWithData()添加到页面的模板将没有Template.parentData()上下文。

作为一种解决方法,仍然可以将其作为参数传递,如下所示:

Blaze.renderWithData(Template.myTemplate, {parentDataContext: Template.currentData()})

但请注意不会被动

如果您需要反应性,还有另一种解决方法。您可以在ReactiveDict()(而不是ReactiveVar())中存储要共享的上下文元素,并将其作为参数传递:

Template.myTemplate.rendered = function(){
  this.dataContext = new ReactiveDict()
  this.dataContext.set("contextVariable1", this.data.whatever)
  this.dataContext.set("contextVariable2", this.data.ImAwesome)
  // etc.
  Blaze.renderWithData(Template.myTemplate, {parentDataContext: this.dataContext})
}

这样,您可以在父模板和使用Blaze.render()Blaze.renderWithData()加载的子模板之间共享反应性本地上下文。

相关问题