- Templates
使用模板的方法只需引入handlebars庫即可使用,通過兩個大括號的方式將變量包含起來,對應的數據就會展示到定義好的模板中展示,這塊如果碰上數據想解析成html代碼時可使用三個大括號展示
<script type="text/template" id="my_tem">
<div class="demo">
<h1>{{name}}</h1>
<p>{{content}}</p>
<h2>{{food.like1}}</h2>
{{{dom}}}
</div>
</script>
對應的JS代碼以及數據如下:
var data={
name:'lx',
content:'this is my first tml',
food:{
"like1":'tomato',
"like2":'apple'
},
dom:"<div>直接解析</div>"
};
let tpl=$("#my_tem").html(); //獲取模板內容
let template=Handlebars.compile(tpl); //預編譯模板
let html=template(data); //匹配數據
$("body").append(html); //插入到DOM
- 循環遍歷#each
each方法如同js中的循環一樣,遍歷數據然後插入到模板中,each使用方法如下:
<script id="table-template" type="text/template">
{{#each student}}
<tr>
<td>{{addOne @index}}</td>
<td>ss{{name}}</td>
<td>{{sex}}</td>
<td>{{age}}</td>
</tr>
{{/each}}
</script>
<script type="text/javascript">
var data = {
"student": [
{
"name": "張三",
"sex": "0",
"age": 18
},
{
"name": "李四",
"sex": "0",
"age": 22
},
{
"name": "妞妞",
"sex": "1",
"age": 19
}
]
};
let tpl=$("#table-template").html();
let template=Handlerbars.compile(tpl);
let html=template(data);
Handlebars.registerHelper("addOne",function(index,options){
return parseInt(index)+1;
});
$("body").append(html);
</script>
- Helper函數
在上面的代碼中的addOne @index用來實現對table表格的一個序號標記,這塊用到了Helpers功能函數,通過registerHelper方法來實現,具體的實現方式如代碼可見,在模板中我們通常可以多次使用這個方法來對我們所需要的數據進行一個改變。