'Can't use logical operators in handlebars #if statement?

I have the following code:

{{#if true}} An {{else}} A {{/if}

That's the entire template. It's loading fine. But notice the #if condition is simply true. If I put anything other than a literal there, it doesn't work. Any variable I put, any sort of programmatic expression like {{#if 3 > 5}}, it gives me a Parser Error:

Error: Parse error on line 36:
{{#if 3 > 5 }} An {{else}} A
---------------------^
Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'INVALID'

I can't figure that out. I even reduced it to just {{#if 3 > 5}} A {{/if}} and it still gives a parser error.

So I thought maybe you have to use a helper for this sort of thing, but I can't get any helper I register to work either.



Solution 1:[1]

Turns out the #if helper can only test for properties to be true or false – not arbitrary expressions[source], so you have to do everything with helpers. Just write a function to compare things with logical operators and return true or false.

And to save you some trouble, the syntax for calling helpers doesn't use parentheses, either....arguments are space-separated like in rails. So it looks like:

{{myHelperFunction myarg1 myarg2}}

And if you want to nest helpers, you need parens:

{{myOuterHelper (myInnerHelper myarg1 myarg2)}}

Last tip from me, if you want to nest your helper with an #if, you need parens, too:

{{#if (myHelper myarg1 myarg2)}} content {{/if}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1