[关闭]
@hx 2018-04-06T19:17:47.000000Z 字数 627 阅读 843

HandleBars

前端


基本框架

  1. let template = $('#card').html(); // #card是在script中想写的template
  2. // <script id="card" type="text/x-handlebars-template">
  3. let f = Handlebars.compile(template);
  4. let h = f(data);
  5. $('#app').html(h); // #card是需要插入的html锚点。

遍历数组

  1. {{#each this}}
  2. {{/each}}
  3. // 遍历下标
  4. {{@index}}
  5. // 遍历上层上下文下标
  6. {{@../index}}

修改上下文

  1. {{#with obj}}
  2. {{/with}}

判断

  1. {{#if boolean}}
  2. {{/if}}

Helper

内联Helper

将数字序号转换成中文序号

  1. {{chinese @index}}
  2. Handlebars.registerHelper('chinese', (val) => ['一', '二', '三'][val]);

块Helper

判断是否为第二个,如果是,则文字变成红色

  1. <div class="card" {{#isTwo @index}} style="color:red" {{/isTwo}}>
  2. ...
  3. </div>
  1. Handlebars.registerHelper('isTwo', (val, options) => {
  2. if (val === 1) {
  3. return options.fn(this);
  4. }
  5. });

注释

{{!注释内容}}

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注