近来项目中用到hbs模版,连系express,觉得还不错。个中,helper是handlebar的中心,为了让本身用得更爽,经由汇集和揣摩,留下一手helper,亲测有用。
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页面母版)
<head>
<meta charset="UTF-8">
<title>{{{block "title"}}}</title>
</head>
page1.hbs(子页面)
{{#extend "title"}}
测试题目
{{/extend}}
=>
<head>
<meta charset="UTF-8">
<title>测试题目</title>
</head>
2. 包括
源码
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}}
=>
'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}}
=>
1、2、3、4、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