handlebars前端模板学习

最简单的用法

1
2
3
4
5
6
7
8
<div>
<h1>
{{title}}
</h1>
<p>
{{content}}
</p>
</div>

嵌入数据

1
2
3
4
const 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
8
HandleBars.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>'
})

编译后即可生成html

1
2
3
4
5
<ul>
<li>wang hh</li>
<li>li sd</li>
<li>zhao ks</li>
</ul>

路径

模板数据

1
2
3
4
5
6
var content = {
title: "Hello",
author: {
name: "onion",
}
}

1
2
3
4
5
6
7
8
<div>
<h1>
{{title}}
</h1>
<h2>
By {{author.name}}
</h2>
</div>

注释

1
2
3
<div class="entry">
{{! 我是注释 }}
</div>

Helpers

Handlebars.registerHelper方法自定义Helper方法

1
2
3
4
5
6
7
8
9
10
var article = {
author: {
firstName: 'wang',
lastName: 'huahua',
},
content: "I'm whh",
}
Handlebars.registerHelper('getFullname', function(person) {
return person.firstName + " " + person.lastName;
})

1
2
3
4
<div class="article">
<h1>By {{getFullname author}}</h1>
<div class="content">{{content}}</div>
</div>

输出结果为

1
2
3
4
<div class="article">
<h1>By wang huahua</h1>
<div class="content">I'm whh</div>
</div>

内置helper

如if each等等

一些常用实例

  1. 引入组件模板

    1
    {{> common-header.hbs}}
  2. 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 }}
  3. compare

    1
    {{#compare msg "!==" ""}}
  4. each

    1
    2
    3
    {{#each imgList}}
    <img src="{{url}}">
    {{/each}}
  5. index(添加索引)

    1
    2
    3
    {{#each studentList}}
    <li data-index="{{@index}}"></li>
    {{/each}}
0%