10

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

  • 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>

Is there a better solution ?

Phillip Cloud
  • 24,919
  • 11
  • 68
  • 88
Vincent
  • 125
  • 5

2 Answers2

13

You can always extend the current context in a helper:

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

And use it like this:

<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;
});

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.

David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • Can you please elaborate a bit more? Why do you nee to do _.clone(this)? – massimosgrelli Apr 21 '16 at 06:23
  • Why do you nee to do _.clone(this)? What if I add result to a child data context? Something like iconContext : function(childDataLikeMsgPost) {... childDataLikeMsgPost.withIcon=...} That would help me a lot – massimosgrelli Apr 21 '16 at 06:29
7

Building on David's second option to allow for multiple attributes:

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

and then in javascript:

Template.registerHelper('extendContext', function(data) {
  var result = _.clone(this);
  _.each(data.hash, function(value, key) {
    result[key] = value;
  })
  return result;
})
Community
  • 1
  • 1
Lance Anderson
  • 493
  • 4
  • 9