最近項目中用到hbs模版,結合express,感受還不錯。其中,helper是handlebar的核心,爲了讓本身用得更爽,通過蒐集和琢磨,留下一手helper,親測有效。express
1. block與extend測試
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; });
layout.hbs(page1頁面母版)this
<head> <meta charset="UTF-8"> <title>{{{block "title"}}}</title> </head>
page1.hbs(子頁面)code
{{#extend "title"}} 測試標題 {{/extend}}
=>源碼
<head> <meta charset="UTF-8"> <title>測試標題</title> </head>
2. 包含it
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); } });
{{#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}}
=>io
'1' include in '1,2,3' --- 'b' not include in 'c,d'
3. 等於function
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. 大於等於meta
hbs.registerHelper('egt', function (args1, args2, context) { if (args1 >= args2) { return context.fn(this); } else { return context.inverse(this); } });
5. 大於
hbs.registerHelper('gt', function (args1, args2, context) { if (args1 > args2) { return context.fn(this); } else { return context.inverse(this); } });
6. 小於等於
hbs.registerHelper('elt', function (args1, args2, context) { if (args1 <= args2) { return context.fn(this); } else { return context.inverse(this); } });
7. 小於
hbs.registerHelper('lt', function (args1, args2, context) { if (args1 < args2) { return context.fn(this); } else { return context.inverse(this); } });
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