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.
I don't think this is going to work. If I understand the handlebars documentation correct, the #if is a registered block-helper itself and does not take another registered helper as an argument.
According to the documentation you might implement it like that
Handlebars.registerHelper('ifItemSelected', function(item, block) {
var selected = false;
// lots of logic that determines if item is selected
if(selected) {
return block(this);
}
});
Afterwards you should be able to call it with
{{#ifItemSelected SomeItem}}
This was selected
{{/ifItemSelected}
but you have to make sure SomeItem has the proper format. I don't see a way to use a registered handler as conditional in an if-statement.