Switch Case with Default in Handlebars. Js
I Want to Implement a Custom Switch Case with Default Value with the Help of the Register Helper Function in Handlebarsjs. Example: Html: {{#Switch Value}}...
I want to implement a custom switch case with default value with the help of the Register Helper function in HandlebarsJs.
Example:
HTML:
<div>
{{#switch value}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{#default 'C'}} {{/default}}
{{/switch}}
</div>
JS:(The Register Helper function should work like the below pseudo code)
switch(val) {
case 1:
return 'A';
break;
case 2:
return 'B';
break;
default:
return 'C';
}
4 Answers
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 to test the code. (Give {}
for Context)
Must Read
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);
}
});
==========================================================================