3

How can I have an inline conditional expression in a Handlebars template?

There is a way to do that within a "native" way? I mean, without registering a custom helper?

For example, I've been playing with the code (with the parenthesis and without them):

<select name="alignment">
     <option value="left" {{ #if (options.text_alignment == 'left') }}selected="selected"{{ /if }}>Left</option>
     <option value="center" {{ #if (options.text_alignment == 'center') }}selected="selected"{{ /if }}>Center</option>
     <option value="right" {{ #if (options.text_alignment == 'right') }}selected="selected"{{ /if }}>Right</option>
</select>

but it doesn't work at all and throws the error:

Error: Parse error on line 20:
 ...ion value="left" {{ #if (options.text_al
 -----------------------^
 Expecting 'ID', 'DATA', got 'INVALID'
    [Break On This Error] 

throw new Error(str);

So, how I can have an inline conditional statement in the form of if/else structures or the classic ternary operator (var == value)?'yes':'no'

Thanks in advance.

Diosney
  • 10,520
  • 15
  • 66
  • 111

3 Answers3

10

Finally, I was able to accomplish that but I've to say it, in a not nice way :(

I registered a custom helper like the following:

    // Need to mark selected option inside a select.
    Handlebars.registerHelper('select', function(variable, value) {
        if (variable == value) {
            return new Handlebars.SafeString('selected=selected');
        }
        else {
            return '';
        }
    });

This custom helper can be used like that:

    {{select option 'right'}}

where option is the variable to be tested and 'right' the value against it is tested.

If later anyone come with a nice solution that works also for radios & checkboxes please, add the answer that I will be happy to vote up them :D

Visne
  • 357
  • 3
  • 10
Diosney
  • 10,520
  • 15
  • 66
  • 111
3

inline if statement:

<div class="message {{if isImportant 'important' 'unimportant'}}"></div>
Community
  • 1
  • 1
vsync
  • 118,978
  • 58
  • 307
  • 400
0

As far as I know, this is the only way you can do it without registering a custom helper.

Handlebars.js Else If

Community
  • 1
  • 1
Homer6
  • 15,034
  • 11
  • 61
  • 81
  • Can you post a sample like mine with a select and options to be selected depending on the variable options? The above code I posted doesn't work for me. Thanks. – Diosney Aug 10 '13 at 20:45