将参数传递到模板而不覆盖数据上下文 [英] Pass parameters to template without overriding data context

查看:45
本文介绍了将参数传递到模板而不覆盖数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to pass a new parameter to a template with keeping it's original data context.

  • 原始数据上下文:{message:"hello"} {{> myTemplate withIcon=True}}
  • 数据上下文用{withIcon:True}覆盖
  • original data context : {message:"hello"} {{> myTemplate withIcon=True}}
  • data context is overriden with {withIcon:True}

当然,我的解决方案是像这样包装数据.

Acually my solution is to wrap data like this.

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

有更好的解决方案吗?

推荐答案

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

You can always extend the current context in a helper:

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

并像这样使用它:

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

或者,您可以创建一个更通用的助手,如下所示:

Alternatively, you could create a more generic helper like this:

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

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

And then choose the key/value pairs from within the html of any template:

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

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

Either solution is more desirable than hiding the original data in a separate field, as it keeps the child template generic.

这篇关于将参数传递到模板而不覆盖数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆