问题
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';
}
回答1:
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;
}
});
回答2:
Just if you want to convert key to value.
module.exports = function(input, cases, values) {
const caseArray = cases.split(',')
const valueArray = values.split(',')
const defaultValue = caseArray.length < valueArray.length ? valueArray[valueArray.length-1] : "";
return caseArray.indexOf(input) > -1? valueArray[caseArray.indexOf(input)] : defaultValue
};
{{switch "Y" "Y,N,D", "YES,NO,DELETED,-"}} // YES
{{switch "Hi" "Y,N,D", "YES,NO,DELETED,-"}} // -
来源:https://stackoverflow.com/questions/53398408/switch-case-with-default-in-handlebars-js