在handlebars.js中默认切换大小写

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)

San*_*raj 6

请仔细阅读以下示例,它将逐步指导您添加具有默认值的开关盒并打破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)