Handlebars的安装是比较简单和方便的;handlebars是一个纯JS库,因此你可以像使用其他JS脚本一样用script标签来包含handlebars.js
<script src="jquery.min.js"></script>
<script type="text/javascript" src=".js/handlebars.js"></script>
将对象数据渲染到页面上
js代码
//用jquery获取模板
var tpl = $("#tpl").html();
//预编译模板
var template = Handlebars.compile(tpl);
//模拟json数据
var context = { name: "XXX", content: "this is Handlebars"};
//匹配json内容
var aaa = template(context);
//输入模板
$("#wrap").html(aaa);
模板结构
<script id="tpl" type="text/x-handlebars-template">
<div class="demo">
<h1>{{name}}</h1>
<p>{{content}}</p>
</div>
</script>
有时候当你需要对某条表达式进行更深入的操作时,Blocks就派上用场了,在Handlebars中,你可以在表达式后面跟随一个#号来表示Blocks,然后通过{{/表达式}}来结束Blocks。 如果当前的表达式是一个数组,则Handlebars会“自动展开数组”,并将Blocks的上下文设为数组中的元素。
<ul>
{{#arr_data}}
<li>{{language}}</li>
{{/arr_data}}
</ul>
以下为json数据
{
arr_data: [
{language: "hello"},
{language: "word"},
{language: "handlebars"}
]
}
上面的代码会自动匹配arr_data数据并展开数据
Handlebars的if判断只能判断true和false,没办法进行这种a===10的逻辑判断。
#模板
{{#if isTrue}} <p>isTrue</p> {/if}}
{{#if email}} <p>{{email}}</p> {{else}} <p>is not email</p> {{/if}}
{{#if num}} <p>{{num}}</p> {{/if}}
{{#if data1}} {{else}} <p>没有这个字段</p> {{/if}}
#json数据
{
isTrue: true,
email: '',
num: '0'
};
#页面效果
isTrue
is not email
0
没有这个字段
说明:
{{#with}}一般情况下,Handlebars模板会在编译的阶段的时候进行context传递和赋值。使用with的方法,我们可以将context转移到数据的一个section里面(如果你的数据包含section)。这个方法在操作复杂的template时候非常有用。【简单的说就是,with可以判断这几数据有没有; 个人感觉和if挺像的】
{{#with author}}
有author就显示里面的内容,没有就不显示
{{/with}}
Handlebar支持路径访问,Handlebar还支持嵌套的路径,使得能够查找嵌套低于当前上下文的属性
可以通过.来访问属性也可以使用../,来访问父级属性。 例如:(使用.访问的例子)【经常搭配着with一起用的】
#模板
<h1>{{author.id}}</h1>
#json
{
title: "this is title",
author: {
id: 47,
name: "XXX"
},
body: "this is body"
}
遍历可以算是一个最常用的功能,对于很多数据的展示都是需要用到each的。Handlebar的遍历对于数组和对象都适用。
#模板
{{#each this}}
<p>{{this.name}}:{{this.age}}</p>
{{else}}
<p>no data</p>
{{/each}}
#json
[
{name: 'aaa', age: 23 },
{name: 'bbb', age: 55 }
]
遍历的一些小技巧
有时候,后台传来的一篇文章是富文本内容,而我们想要将其转换为htnl输出怎么办呢?“{{}}”输出默认转义Html,几乎所有的模板引擎输出默认都是转义Html的,避免xss攻击。如果你想避免转义,请这样用“{{{}}}”
#模板
<div>{{richText}}</div>
<div>{{{richText}}}</div>
#数据
var data = {
richText: '<div>this is content</div>'
};
#模板
<p>{{format time}}</p>
#Helpers
Handlebars.registerHelper('format', function (date, options) {
return new Date(date).toLocaleString();
});
#数据
{"time":1450576000281}
#模板
{{#equal data1 data2}}
<p>两个数相等</p>
{{else}}
<p>不相等</p>
{{/equal}}
#js
Handlebars.registerHelper("equal",function(v1,v2,options){
if(v1 == v2){
//满足添加继续执行
return options.fn(this);
}else{
//不满足条件执行{{else}}部分
return options.inverse(this);
}
});
#模板
<p>{{safe}}</p>
#js
Handlebars.registerHelper('safe', function () {
return new Handlebars.SafeString('<div>safe string</div>')
});
Handlebars也可以使用注释写法如下
{{! 单行注释 }}
{{!-- 多行注释 --}}
共享同一个模板内容,有些公共部分希望一次书写,然后就能重复使用了;类似一些include的功能; 不需要也能调用Helper的方法
#模板
<p>{{> footer}}</p>
#Helper
Handlebars.registerPartial('footer', function () {
return new Handlebars.SafeString('<div>This is footer</div>')
});
Handlebars官网的很多内置的helper以及功能可以参考看一下Handlebars官网,入门有时候还是容易的,但是深入学习需要的时间和经验。