最近项目中用到hbs模版,结合express,感受还不错。其中,helper是handlebar的核心,为了让本身用得更爽,通过搜集和琢磨,留下一手helper,亲测有效。express
1. block与extend测试
源码this
let blocks = {}; hbs.registerHelper('extend', function (name, context) { let block = blocks[name]; if (!block) { block = blocks[name] = []; } block.push(context.fn(this)); }); hbs.registerHelper('block', function (name) { let val = (blocks[name] || []).join('\n'); blocks[name] = []; return val; });
使用code
layout.hbs(page1页面母版)源码
<head> <meta charset="UTF-8"> <title>{{{block "title"}}}</title> </head>
page1.hbs(子页面)it
{{#extend "title"}} 测试标题 {{/extend}}
=>io
<head> <meta charset="UTF-8"> <title>测试标题</title> </head>
2. 包含function
源码遍历
hbs.registerHelper('include', function (args1, args2, context) { let array = args2.split(','); if (!_.isArray(array)) { return context.inverse(this); } if (_.includes(array, args1) || _.includes(array, args1.toString())) { return context.fn(this); } });
使用meta
{{#include '1' '1,2,3'}} '1' include in '1,2,3' {{else}} '1' not include in '1,2,3' {{/include}} --- {{#include 'b' 'c,d'}} 'b' include in 'c,d' {{else}} 'b' not include in 'c,d' {{/include}}
=>
'1' include in '1,2,3' --- 'b' not include in 'c,d'
3. 等于
源码
hbs.registerHelper('equal', function (args1, args2, context) { if (args1 === args2) { //知足添加继续执行 return context.fn(this); } else { if (typeof(args1) === 'number' && args1.toString() === args2.toString()) { return context.fn(this); } //不知足条件执行{{else}}部分 return context.inverse(this); } });
使用
{{#equal 1 2}} 1 === 2 {{else}} 1 !== 2 {{/equal}}
=>
1 !== 2
4. 大于等于
源码
hbs.registerHelper('egt', function (args1, args2, context) { if (args1 >= args2) { return context.fn(this); } else { return context.inverse(this); } });
使用同equal
5. 大于
源码
hbs.registerHelper('gt', function (args1, args2, context) { if (args1 > args2) { return context.fn(this); } else { return context.inverse(this); } });
使用同equal
6. 小于等于
源码
hbs.registerHelper('elt', function (args1, args2, context) { if (args1 <= args2) { return context.fn(this); } else { return context.inverse(this); } });
使用同equal
7. 小于
源码
hbs.registerHelper('lt', function (args1, args2, context) { if (args1 < args2) { return context.fn(this); } else { return context.inverse(this); } });
使用同equal
8. 结合each实现遍历N次
源码
hbs.registerHelper('count', function (args1, context) { let array = []; for (let i = 1; i <= args1; i++) { array.push(i); } return context.fn(array); });
使用
{{#count 5}} {{#each this |index|}} {{index}}、 {{/each}} {{/count}}
=>
一、二、三、四、5
9. 加法
源码
hbs.registerHelper('add', function (args1, args2) { return args1 + args2; });
使用
{{add 1 2}}
=>
3
10. 减法
源码
hbs.registerHelper('sub', function (args1, args2) { return args1 - args2; });
使用
{{sub 3 1}}
=>
2