在 meteor/blaze 模板中过滤变量

filtering variables in meteor/blaze template

假设我有一个要在其他 Meteor 模板中使用的 Meteor 模板。

<template name="helpsout">
  <p><b>{{text}}</b></p>
</template>

假设我想从另一个模板 needshelp 调用此助手,该模板获取字符串数组 arr 作为助手,并且我想在每个元素上调用 helpsout 模板arr 的,但首先要修改它的是在 "this needs help: " 之前。我想写这样的东西:

<template name="needshelp">
    {{#each arr}}
      {{> helpsout text="this needs help: {{this}}"}}
    {{/each}}
</template>

但是 {{this}} 没有被插值,它最终将 text 设置为文字 "this needs help: {{this}}"

有没有办法不用将 helpsout 的内容直接复制到 needshelp 中? (你可以想象 helpsout 实际上是一个复杂的模板,它被其他几个模板使用,所以我们不想将它复制到它被使用的每个地方。)看起来有子表达式可以做到,但 AFAIK Meteor 目前不支持此功能。

你有两个选择:

前缀很常见

如果您的应用程序中的常见模式是 helpsout 应该使用某种正文文本和一些前缀文本来调用,我会修改 helpsout 的上下文,以便它需要一个body 和一个可选的 prefix 像这样:

<template name="needshelp">
  {{#each arr}}
    {{> helpsout prefix="this needs help: " body=this}}
  {{/each}}
</template>
Template.helpsout.helpers({
  text: function() {
    return (this.prefix || '') + this.body;
  }
});

前缀不常见

如果您希望保持代码不变 helpsout,那么您可以在 needshelp 模板中使用额外的助手来设置上下文:

<template name="needshelp">
  {{#each arr}}
    {{> helpsout text=helpText}}
  {{/each}}
</template>
Template.needshelp.helpers({
  helpText: function() {
    return "this needs help: " + this;
  }
});