如何在 Blaze 模板或模板助手中获取 "root" 数据

How to get the "root" data in a Blaze template or template helper

假设我必须访问包含相同嵌套模板的页面:

第 1 页:

>rootTeplate
  >fooTemplate
    >barTemplate

第2页:

>rootTeplate
  >barTemplate

我如何编写一个模板帮助程序来访问 barTemplate 中 rootTemplate 的数据?我知道我可以使用 ../ 访问父上下文,但在这种情况下,barTemplate 不知道它必须返回多少级别。

您需要确定要返回多少个级别。在 barTemplate 的帮助程序中,您可以使用 Template.parentData

Template.barTemplate.helpers({
     something: function() {
         var parentDatas = Template.parentData()

         //If there are two levels
         var parentDatas = Template.parentData(2)
     }
});

您需要确定要访问的级别,您可以将此数字插入 Template.parentData

如果您不确定需要返回多少级别,则可能不值得使用此范例。考虑使用来自路由器的 data 上下文或 Session 哈希。

在这种情况下,您可以使用 Router.current().data().

从 iron:router 访问数据上下文
Template.barTemplate.helpers({
  var data = Router.current() && Router.current().data();
  if(data)
    // use it