最简单的用法
1 | <div> |
嵌入数据1
2
3
4const template = require('Handlebars').template;
var context = {title: 'Yo', content: "Hello world!"};
var html = template(context);
生成结果1
2
3
4
5
6
7
8<div>
<h1>
Yo
</h1>
<p>
Hello world!
</p>
</div>
嵌入html
如果想要嵌入的值不需要改变则直接使用三个花括号。1
2
3
4
5
6
7
8<div>
<h1>
{{title}}
</h1>
<p>
{{{body}}}
</p>
</div>
块级表达式
1 | {{#list people}} {{firstName}} {{lastName}} {{/list}} |
嵌入如下数据1
2
3
4
5
6
7{
people: [
{firstName: 'wang', lastName: 'hh'},
{firstName: 'li', lastName: 'sd'},
{firstName: 'zhao', lastName: 'ks'},
]
}
创建一个helper函数1
2
3
4
5
6
7
8HandleBars.registerHelper('list', function(items, options){
var out = '<ul>'
for(let i = 0; i < items.length; i++){
out = out + '<li>' + options.fn(items[i]) + '</li>';
}
return out + '</ul>'
})
编译后即可生成html1
2
3
4
5<ul>
<li>wang hh</li>
<li>li sd</li>
<li>zhao ks</li>
</ul>
路径
模板数据1
2
3
4
5
6var content = {
title: "Hello",
author: {
name: "onion",
}
}
1 | <div> |
注释
1 | <div class="entry"> |
Helpers
Handlebars.registerHelper
方法自定义Helper方法1
2
3
4
5
6
7
8
9
10var article = {
author: {
firstName: 'wang',
lastName: 'huahua',
},
content: "I'm whh",
}
Handlebars.registerHelper('getFullname', function(person) {
return person.firstName + " " + person.lastName;
})
1 | <div class="article"> |
输出结果为1
2
3
4<div class="article">
<h1>By wang huahua</h1>
<div class="content">I'm whh</div>
</div>
内置helper
一些常用实例
引入组件模板
1
{{> common-header.hbs}}
if … else
1
2
3
4
5
6
7
8
9
10{{#if a }}
<h2>title</h2>
<div>
content1
</div>
{{else }}
<div>
content2
</div>
{{/if }}compare
1
{{#compare msg "!==" ""}}
each
1
2
3{{#each imgList}}
<img src="{{url}}">
{{/each}}index(添加索引)
1
2
3{{#each studentList}}
<li data-index="{{@index}}"></li>
{{/each}}