Switch case with default in handlebars.js
Please go through the below examples, it will guide you step by step to add the switch case with default value and break in HandlebarsJs.
Use the link http://tryhandlebarsjs.com/ to test the code. (Give {}
for Context)
Switch case
Handlebars Template:
<div>
{{#switch 'a'}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{/switch}}
</div>
Register Helper functions:
Handlebars.registerHelper('switch', function(value, options) {
this.switch_value = value;
return options.fn(this);
});
Handlebars.registerHelper('case', function(value, options) {
if (value == this.switch_value) {
return options.fn(this);
}
});
==========================================================================
Switch case with default:
Handlebars Template:
<div>
{{#switch 'a'}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{#default '188'}} {{/default}}
{{/switch}}
</div>
Register Helper functions:
Handlebars.registerHelper('switch', function(value, options) {
this.switch_value = value;
return options.fn(this);
});
Handlebars.registerHelper('case', function(value, options) {
if (value == this.switch_value) {
return options.fn(this);
}
});
Handlebars.registerHelper('default', function(value, options) {
return true; ///We can add condition if needs
});
==========================================================================
Switch case with default and break
Handlebars Template:
<div>
{{#switch 'a'}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{#default '188'}} {{/default}}
{{/switch}}
</div>
Register Helper functions:
Handlebars.registerHelper('switch', function(value, options) {
this.switch_value = value;
this.switch_break = false;
return options.fn(this);
});
Handlebars.registerHelper('case', function(value, options) {
if (value == this.switch_value) {
this.switch_break = true;
return options.fn(this);
}
});
Handlebars.registerHelper('default', function(value, options) {
if (this.switch_break == false) {
return value;
}
});
If all you need is an if
-else if
-else
structure, consider to use the built-in if
/else
helpers (see Helpers: Conditionals on "chained" conditionals) and define only the comparison operation in your own helper.
Helper
Handlebars.registerHelper('isEqual', (value1, value2, options) => {
return value1 === value2;
});
Template
<div>
{{#if (isEqual value 'a')}}
A
{{else if (isEqual value 'b')}}
B
{{else}}
C
{{/if}}
</div>
Initially answered here.