【问题标题】:Pass parameters to template without overriding data context将参数传递给模板而不覆盖数据上下文
【发布时间】:2023-03-22 00:37:01
【问题描述】:

我想将新参数传递给模板,同时保留其原始数据上下文。

  • 原始数据上下文:{message:"hello"} {{> myTemplate withIcon=True}}
  • 数据上下文被 {withIcon:True} 覆盖

实际上我的解决方案是像这样包装数据。

<code>
{{> myTemplate originalData=this withIcon=True}}
</code>

有没有更好的解决方案?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您始终可以在帮助程序中扩展当前上下文:

    Template.parentTemplate.helpers({
      iconContext: function() {
        var result = _.clone(this);
        result.withIcon = true;
        return result;
      }
    });
    

    并像这样使用它:

    <template name="parentTemplate">
      {{> myTemplate iconContext}}
    </template>
    

    或者,您可以像这样创建一个更通用的帮助器:

    Template.registerHelper('extendContext', function(key, value) {
      var result = _.clone(this);
      result[key] = value;
      return result;
    });
    

    然后从任何模板的 html 中选择键/值对:

    <template name="parentTemplate">
      {{> myTemplate extendContext 'withIcon' true}}
      {{> myTemplate extendContext 'isAwesome' false}}
    </template>
    

    这两种解决方案都比将原始数据隐藏在单独的字段中更可取,因为它使子模板保持通用性。

    【讨论】:

    • 您能详细说明一下吗?你为什么要做_.clone(this)?
    • 你为什么要做_.clone(this)?如果我将结果添加到子数据上下文会怎样?类似 iconContext : function(childDataLikeMsgPost) {... childDataLikeMsgPost.withIcon=...} 这对我有很大帮助
    【解决方案2】:

    基于David's second option 允许多个属性:

    <template name="parentTemplate">
      {{> myTemplate extendContext withIcon=true label="Has Icon" }}
      {{> myTemplate extendContext withIcon=false label="No Icon" }}
    </template>
    

    然后在javascript中:

    Template.registerHelper('extendContext', function(data) {
      var result = _.clone(this);
      _.each(data.hash, function(value, key) {
        result[key] = value;
      })
      return result;
    })
    

    【讨论】:

    • 应该也可以:return _.extend({}, this, data.hash);
    猜你喜欢
    • 2020-11-17
    • 2021-09-10
    • 2016-03-26
    • 2015-10-12
    • 1970-01-01
    • 2018-05-07
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多