I have started using Handlebars.js. It seems that there is no built in conditionals like else if. I want to have something like this
{{#if type.one }}
do something ... IF
{{else if type.two}}
do something ... ELSE IF
{{else}}
do something ... ELSE
{{/if}}
But this doesn't work. How do I do ELSE IF with handlebars? Is writing a custom helper is the only option ? If yes then please provide some pointers to write this helper.
Below there is an example of code which creates two super simple custom helpers which accept one argument: /* * Custom theme helpers for Handlebars. js */ let themeHelpers = { test1: function(value) { return "TEST1 " + value; }, test2: function(value) { return "TEST2 " + value; } }; module.
The Handlebars {{if}} block helper is one of the built-in helpers that will conditionally render a block of code.
You can't do this with a custom helper as Handlebars if-ish helpers only understand two parts: the "if" part and the "else" part. You can nest things though:
{{#if type.one}}
do something ... IF
{{else}}
{{#if type.two}}
do something ... ELSE IF
{{else}}
{{#if type.three}}
...
{{else}}
...
{{/if}}
{{/if}}
{{/if}}
That sort of thing will get nasty fast so you probably don't want to do that. A better approach would (as usual with Handlebars) be to push the logic into your JavaScript so that at most one of type.one
, type.two
, type.three
, ... would be true; then you could:
{{#if type.one}}
...
{{/if}}
{{#if type.two}}
...
{{/if}}
{{#if type.three}}
...
{{/if}}
If you have a lot of options for type
or if the bodies in your {{#if}}
s are complicated, you could switch to partials. You'd have to add a custom helper to build a partial name based on a template variable though; something like this:
Handlebars.registerHelper('show_type', function(type) {
var types = ['one', 'two', 'three'];
var partial;
for(var i = 0; i < types.length; ++i) {
if(!type[types[i]])
continue;
partial = '_partial_' + types[i];
break;
}
if(partial)
return Handlebars.partials[name](this);
else
return '';
});
and then, assuming your partials are all registered and consistently named, you could say:
{{show_type type}}
Since Handlebars 3.0 the syntax described by OP does work out of the box! See: https://github.com/wycats/handlebars.js/pull/892 for more information.
Note: For Ember, since version 1.10 and up this does work too. See also: http://emberjs.com/blog/2015/02/07/ember-1-10-0-released.html#toc_chained-else-blocks
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