8

在流星中,我可以像这样设置各种模板助手:

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>

那是行不通的。谢谢

4

2 回答 2

12

您可以在调用模板时设置模板的上下文:

{{> story data}}

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

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

{{#with data}}
  {{title}}
{{/with}}
于 2012-10-25T07:20:11.933 回答
5

您绝对正确,但错过了以您定义的方式使用模板变量。正如Template.story.data定义为返回一个对象,您应该像使用对象一样使用它:

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

瞧。当然,每个模板变量可以容纳的不仅仅是一个字符串。

于 2012-10-22T10:01:49.230 回答