Diskdrive
Diskdrive

Reputation: 18825

Can I pass a helper into a handlebar function?

To prevent having to build the same html for a label and text combination, I have a Handlebar function to generate the HTML for me.

So for example I have this

                    {{{labelSpan 'Input Type' inputType}}}
                    {{{labelSpan 'Formula' showFriendlyFormula formula }}}

And the handlebar function

UI.registerHelper('labelSpan', function(label, value){
return '<p> <label>' + label + ':</label><br> <span>' + value + '</span></p>';

});

Now inputType is fine because it is part of the context.

However, showFriendlyFormula is derived from another helper method because essentially I need to do a whole of additional things to this

    Template.create.helpers({
  showFriendlyFormula: function(formula) {
    return share.convertFormulaToAnotherInputField(formula);
  }
});

Obviously, calling {{{labelSpan 'Formula' showFriendlyFormula formula }}} is going to fail, so is there a way for me to pass into labelSpan, the output of showFriendlyFormula(formula)

Upvotes: 0

Views: 424

Answers (1)

sbking
sbking

Reputation: 7680

Spacebars isn't really expressive enough to do this (likely by design, as templating engines generally shouldn't implement too much logic). You could try something like:

Template.create.helpers({
  friendlyFormula: function() {
    return share.convertFormulaToAnotherInputField(this.formula);
  }
});

{{{labelSpan 'Formula' friendlyFormula}}}

Edit: Or, as Peppe L-G said, you can change the context using a {{#with}} block and then pass that context into the other helper:

{{#with showFriendlyFormula formula}}
  {{labelSpan 'Formula' this}} <!-- or {{labelSpan 'Formula' .}} -->
{{/with}}

You could also make your labelSpan as a block helper instead of an inline helper. Something like this:

<template name="labelSpan">
  <p>
    <label>{{this}}</label><br>
    <span>{{Template.contentBlock}}</span>
  </p>
</template>

Which you can then use like:

{{#labelSpan 'Formula'}}
  {{showFriendlyFormula formula}}
{{/labelSpan}}

Here's the full documentation for Spacebars.

Upvotes: 1

Related Questions