Meteor设置整体模板上下文

8
在 Meteor 中,我可以像这样设置各种模板助手:
Template.story.title = function () {
  return "title";
};
<template name="story">
  <h3>{{title}}</h3>
  <p>{{description}}</p>
</template>

这很好,但如果我有许多变量,我不想逐个设置它们,我希望将上下文传递给主模板。如何实现?
Template.story.data = function () {
  return {title:"title", description:"desc"};
};
<template name="story">
  <h3>{{title}}</h3>
  <p>{{description}}</p>
</template>

那行不通。谢谢。

2个回答

12

当您调用模板时,可以设置其上下文:

{{> story data}}

Template.outerTemplate.data = function() { 
  return {title:"title", description:"desc"};
}

或者您可以使用{{#with}}来动态设置模板上下文:

{{#with data}}
  {{title}}
{{/with}}

5

你的做法是正确的,但是你没有按照你定义的方式使用模板变量。由于Template.story.data被定义为返回一个对象,所以你应该像使用对象一样使用它:

<template name="story">
  <h3>{{data.title}}</h3>
  <p>{{data.description}}</p>
</template>

看这里。当然,每个模板变量都不仅仅可以存储字符串。


2
谢谢,这个可以用,但是,应该有一种方法来设置主上下文吧?Meteor文档说this是默认上下文。应该有一种方法来设置this而不是data。谢谢。 - Harry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接