一個使用了就會愛上的模板,真的很方便,強烈推薦。靜態(tài)頁面是房子的一個骨架,動態(tài)數(shù)據(jù)就是家里的門,家里的窗,家里的沙發(fā)...這些可以隨之而動的東西,想讓其怎么動,它就能怎么動。
從后臺請求回來數(shù)據(jù),(1.使用字符串拼接的方式2.es6模板字符串),渲染到頁面。我只使用過這兩種方法,第一種方法個人覺得操作繁瑣,頁面中大量的str+=“”頁面很亂,寫錯一個符號,整個都渲染不出來。第二種方法很方便可以讓頁面html保持原有格式,直接反引號進行操作(str+=${obj1[i].h_year})不足的是目前瀏覽器對于es6的支持不足,需要用編譯工具(babel)編譯成es5瀏覽器才能認識它。handlebars模板可以讓html保持原有格式,且不需要經(jīng)過編譯,體積小。
注意:handlebars是一款jquery插件
一:引入1.引入jquery 2.引入handlebars
<!--引入jquery/handlebars-->
<script type="text/javascript" src="./js/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="./js/handlebars-v4.0.10.js"></script>
二:寫handlebars模板
注意:在需要渲染的html外層包上script標簽,1.type要寫,且要寫對。2.給這個模板添加一個唯一的id值,不添加會找不到
<tbody class="student-temp">
<script type="text/x-handlebars-template" id="student-temp">
<tr>
<td>aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</script>
</tbody>
三:handlebars的取值 {{變量名}}
<tbody class="student-temp">
<script type="text/x-handlebars-template" id="student-temp">
<tr>
<td>{{name}}</td>
<td>{{age}}</td>
<td>{{gender}}</td>
<td>{{fraction}}</td>
</tr>
</script>
</tbody>
四:渲染數(shù)據(jù)
<script>
// 模擬數(shù)據(jù)
var data = {
"name": "柳2",
"age": '8',
"gender": '女',
"fraction": '89'
};
console.log(data);
// 獲取到handlebars這個模板中的全部html內(nèi)容
var studentTemp = $('#student-temp').html();
// 編譯
var HanStudent = Handlebars.compile(studentTemp);
//把編譯完成的代碼放入到 .student-temp 的這個容器中
$('.student-temp').html(HanStudent(data))
</script>
整個頁面代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
table, th, td {
border: 1px solid red;
text-align: center;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>分數(shù)</th>
</tr>
</thead>
<tbody class="student-temp">
<script type="text/x-handlebars-template" id="student-temp">
<tr>
<td>{{name}}</td>
<td>{{age}}</td>
<td>{{gender}}</td>
<td>{{fraction}}</td>
</tr>
</script>
</tbody>
</table>
<!--引入jquery/handlebars-->
<script type="text/javascript" src="./js/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="./js/handlebars-v4.0.10.js"></script>
<script>
// 模擬數(shù)據(jù)
var data = {
"name": "柳2",
"age": '8',
"gender": '女',
"fraction": '89'
};
console.log(data);
// 獲取到handlebars這個模板中的全部html內(nèi)容
var studentTemp = $('#student-temp').html();
// 編譯
var HanStudent = Handlebars.compile(studentTemp);
//把編譯完成的代碼放入到 .student-temp 的這個容器中
$('.student-temp').html(HanStudent(data))
</script>
</body>
</html>