Using a helper with arguments AS a helper argument in Spacebars

641 views Asked by At

So I am trying use a helper as an argument of another helper in Spacebars. In the example below, 'getResultInfo' is a helper that gets data specific to the arguments passed, and 'formatResult' is a helper that formats its result and the results of other helpers.

<template name="example">
    {{#each collectionResults}}
        Label: {{formatResult getResultInfo this._id 'text'}}
    {{/each}}
</template>

The issue I'm having is that Spacebars thinks that the arguments for 'getResultInfo' are the just second and third arguments for 'formatResult'. I'd really like to keep the helper's functions separate (ie. not having to format the result at the end of the 'getResultInfo' and every other helper that I have). Is there any alternate syntax or method of doing what I'm trying to achieve?

2

There are 2 answers

0
255kb - Mockoon On BEST ANSWER

I think that you cannot chain two helpers with parameters on the second one like you did. Subsequent parameters will still be interpreted as parameters from the first helper.

I see two ways for solving this problem:

1) you could get rid of the parameters and use the data context provided by each. each bind the data context to this so in getResultInfo you could just use this._id directly. But you have to remember that you need this data context each time you use this helper. And this pose a problem with the 'text' parameter which does not depend from the data context.

2) you could create a function corresponding to your getResultInfo helper and use it directly in the formatResult helper like this:

getResultHelper = function(id, text) {
  //do what you want
};

//bind the function to your getResultInfo (example with a global helper)
Template.registerHelper('getResultInfo', getResultHelper);

//use the function in your template helper
Template.example.helpers({
  formatResult: function(format) {
    return getResultHelper(this._id, format);
  }
});

//and finally your template
<template name="example">
  {{#each collectionResults}}
    Label: {{formatResult 'text'}}
  {{/each}}
</template>
0
Elias Thompson On

FYI, this is now possible in Meteor 1.2, via Spacebars sub expressions in Blaze.

<template name="example">
    {{#each collectionResults}}
        Label: {{formatResult (getResultInfo this._id 'text')}}
    {{/each}}
</template>