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.
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
<div class="message {{if isImportant 'important' 'unimportant'}}"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With