San*_*raj 2 javascript handlebars.js
我想借助HandlebarsJs中的Register Helper函数实现switch
case
带有default
值的自定义。
例:
HTML:
<div>
{{#switch value}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{#default 'C'}} {{/default}}
{{/switch}}
</div>
Run Code Online (Sandbox Code Playgroud)
JS:(Register Helper函数应该像下面的伪代码一样工作)
switch(val) {
case 1:
return 'A';
break;
case 2:
return 'B';
break;
default:
return 'C';
}
Run Code Online (Sandbox Code Playgroud)
请仔细阅读以下示例,它将逐步指导您添加具有默认值的开关盒并打破HandlebarsJs。
使用链接http://tryhandlebarsjs.com/来测试代码。(给予{}
背景)
把手模板:
<div>
{{#switch 'a'}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{/switch}}
</div>
Run Code Online (Sandbox Code Playgroud)
注册助手功能:
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);
}
});
Run Code Online (Sandbox Code Playgroud)
================================================== ========================
把手模板:
<div>
{{#switch 'a'}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{#default '188'}} {{/default}}
{{/switch}}
</div>
Run Code Online (Sandbox Code Playgroud)
注册助手功能:
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
});
Run Code Online (Sandbox Code Playgroud)
================================================== ========================
把手模板:
<div>
{{#switch 'a'}}
{{#case 'a'}} A {{/case}}
{{#case 'b'}} B {{/case}}
{{#default '188'}} {{/default}}
{{/switch}}
</div>
Run Code Online (Sandbox Code Playgroud)
注册助手功能:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2600 次 |
最近记录: |