Calling Helper Within If Block in Handlebars Template

Kevin picture Kevin · Jun 12, 2011 · Viewed 25.2k times · Source

I am working with Handlebars.js template engine and am trying to figure out a way to do something like this (contrived example):

{{#if itemSelected "SomeItem"}}
    <div>This was selected</div>
{{/if}

where itemSelected is a registered helper like this:

Handlebars.registerHelper("itemSelected", function(item) {
    var selected = false;
    // Lots of logic that determines if item is selected
    return selected;
});

I get errors when trying to use this syntax for the template, and I cannot find any example showing this kind of thing. I do see simple #if blocks like this...

{{#if myValueInContext}}
    <div>This will show if myValueInContext results in a truthy value.</div>
{{/if}}

But, I can't figure out how to tackle the first example. Maybe I am approaching this wrong.

By the way, I tagged this Mustache as I could not add a Handlebars tag to the question.

Answer

gnowoel picture gnowoel · Jun 23, 2015

You should add parentheses around the embedded helper invocation:

{{#if (itemSelected "SomeItem")}}
    <div>This was selected</div>
{{/if}

I did experiments and verified that it just works.

Not sure if it's mentioned in the Handlebars documentation. I learned the trick from the examples of handlebars-layouts.