DX2003
DX2003

Reputation: 138

filtering variables in meteor/blaze template

Suppose I have a Meteor template that I want to use inside of other Meteor templates.

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

Suppose I want to call this helper from another template needshelp that gets an array of strings arr as a helper, and I want to invoke the helpsout template on each element of arr but modifying it first say by prepending "this needs help: ". I'd like to write something like this:

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

But the {{this}} is not interpolated and it ends up setting text to the literal "this needs help: {{this}}".

Is there a way to do this without copying the contents of helpsout directly into needshelp? (You can imagine that helpsout is actually a complex template that's used by several other templates so we wouldn't want to copy it into each of the places it's being used.) It seems like having subexpressions would do it but AFAIK this isn't currently supported in Meteor.

Upvotes: 0

Views: 416

Answers (1)

David Weldon
David Weldon

Reputation: 64342

You have two choices:

prefix is common

If it's a common pattern in your app that helpsout should be called with some sort of body text along with some prefix text, I would modify the context of helpsout so that it takes a body and an optional prefix like so:

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

prefix is uncommon

If you'd prefer to keep your code as it is with no changes to helpsout then you can use an additional helper in your needshelp template to set the context:

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

Upvotes: 1

Related Questions