流星设置整体模板上下文

Har*_*rry 8 javascript meteor

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

Template.story.title = function () {
  return "title";
};
<template name="story">
  <h3>{{title}}</h3>
  <p>{{description}}</p>
</template>
Run Code Online (Sandbox Code Playgroud)

这很棒但是,如果我有很多变量我不想单独设置它们,我想将上下文传递给主模板.

我怎么做?

Template.story.data = function () {
  return {title:"title", description:"desc"};
};
<template name="story">
  <h3>{{title}}</h3>
  <p>{{description}}</p>
</template>
Run Code Online (Sandbox Code Playgroud)

这不起作用.谢谢

Tom*_*man 12

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

{{> story data}}

Template.outerTemplate.data = function() { 
  return {title:"title", description:"desc"};
}
Run Code Online (Sandbox Code Playgroud)

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

{{#with data}}
  {{title}}
{{/with}}
Run Code Online (Sandbox Code Playgroud)


mat*_*ias 5

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

<template name="story">
  <h3>{{data.title}}</h3>
  <p>{{data.description}}</p>
</template>
Run Code Online (Sandbox Code Playgroud)

瞧.当然,每个模板变量都可以包含多个字符串.

  • 谢谢这个工作,但是,不应该有办法设置主要上下文?meteor docs说`this`是假定的上下文.应该有一种方法来设置`this`而不是`data`.谢谢. (2认同)