【问题标题】:filtering variables in meteor/blaze template在流星/火焰模板中过滤变量
【发布时间】:2015-09-18 16:31:32
【问题描述】:

假设我有一个 Meteor 模板,我想在其他 Meteor 模板中使用它。

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

假设我想从另一个模板needshelp 调用这个帮助器,该模板获取一个字符串数组arr 作为帮助器,并且我想在arr 的每个元素上调用helpsout 模板,但首先修改它在前面加上“这需要帮助:”。我想写这样的东西:

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

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

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

【问题讨论】:

    标签: templates meteor meteor-blaze


    【解决方案1】:

    你有两个选择:

    前缀很常见

    如果您的应用程序中的常见模式是 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;
      }
    });
    

    【讨论】:

    • 谢谢,大卫。因此,如果我理解正确,就不可能做类似“前缀不常见”的方法,而是将所有文本(即前缀)留在模板文件中?为了分离关注点,我希望不要将前缀放入助手中。
    • 很遗憾,不能 - 在设置上下文时不能进行字符串插值或其他任意 js 代码。
    猜你喜欢
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多