forked from theluyuan/Web
129 lines
2.1 KiB
Markdown
129 lines
2.1 KiB
Markdown
|
|
|||
|
|
|||
|
## 模版引擎
|
|||
|
|
|||
|
### 引入
|
|||
|
|
|||
|
我们在使用ajax请求数据时,返回的如果是一个 JSON 格式的字符串,我们需要将其包装到对应的HTML代码中,再添加到页面上,才能看到效果。那么这个包装得过程有没有简单的方法呢?
|
|||
|
|
|||
|
|
|||
|
假设在 js 中有如下数据:
|
|||
|
|
|||
|
|
|||
|
|
|||
|
```javascript
|
|||
|
var obj = {
|
|||
|
name:"fox",
|
|||
|
age:18,
|
|||
|
skill:"卖萌"
|
|||
|
};
|
|||
|
```
|
|||
|
|
|||
|
希望包装为:
|
|||
|
|
|||
|
```html
|
|||
|
<ul>
|
|||
|
<li>姓名:fox</li>
|
|||
|
<li>年龄:18</li>
|
|||
|
<li>爱好:卖萌</li>
|
|||
|
</ul>
|
|||
|
```
|
|||
|
|
|||
|
|
|||
|
我们可以通过模板插件来实现。
|
|||
|
|
|||
|
### 模版插件的原理
|
|||
|
|
|||
|
我们定义一段文本作为模板,读取文本,使用特殊的符号<%= 属性名 %>,通过正则表达式找到这些特殊的符号进行替换,是不是就实现了这样的效果呢?
|
|||
|
|
|||
|
### 常见的模板引擎
|
|||
|
|
|||
|
- BaiduTemplate(百度开发)
|
|||
|
|
|||
|
- ArtTemplate(腾讯开发):[GitHub地址](https://github.com/aui/art-template)、[文档地址](https://aui.github.io/art-template/zh-cn/docs/)。
|
|||
|
|
|||
|
- velocity.js(淘宝开发)
|
|||
|
|
|||
|
- Handlebars
|
|||
|
|
|||
|
|
|||
|
## ArtTemplate
|
|||
|
|
|||
|
|
|||
|
标准语法:
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
```html
|
|||
|
{{if user}}
|
|||
|
<h2>{{user.name}}</h2>
|
|||
|
{{/if}}
|
|||
|
```
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
渲染模板:
|
|||
|
|
|||
|
|
|||
|
```javascript
|
|||
|
var data = {
|
|||
|
title: `标签`,
|
|||
|
list: [`文艺`, `博客`, `摄影`]
|
|||
|
};
|
|||
|
var html = template(`test`, data);
|
|||
|
document.getElementById(`content`).innerHTML = html;
|
|||
|
```
|
|||
|
|
|||
|
|
|||
|
举例:
|
|||
|
|
|||
|
|
|||
|
|
|||
|
```html
|
|||
|
<!DOCTYPE html>
|
|||
|
<html lang="en">
|
|||
|
<head>
|
|||
|
<meta charset="UTF-8">
|
|||
|
<title>Title</title>
|
|||
|
<script src="js/template-native-debug.js"></script>
|
|||
|
<script src="js/jquery-2.2.0.js"></script>
|
|||
|
|
|||
|
<script id="tpl" type="text/html">
|
|||
|
<h3><%= className %></h3>
|
|||
|
<ul>
|
|||
|
<% for(var i = 0; i< students.length;i++) { %>
|
|||
|
<li><%= i+1 %>. <%= students[i] %></li>
|
|||
|
<% } %>
|
|||
|
</ul>
|
|||
|
|
|||
|
</script>
|
|||
|
|
|||
|
<script>
|
|||
|
var data = {
|
|||
|
className:"前端1期",
|
|||
|
students:["张飞","刘备","诸葛亮","甄姬","小乔","汪汪"]
|
|||
|
};
|
|||
|
|
|||
|
$(function (){
|
|||
|
var html = template("tpl",data);
|
|||
|
$("#demo").html(html);
|
|||
|
})
|
|||
|
</script>
|
|||
|
</head>
|
|||
|
<body>
|
|||
|
|
|||
|
<div id="demo">
|
|||
|
|
|||
|
</div>
|
|||
|
</body>
|
|||
|
</html>
|
|||
|
```
|
|||
|
|
|||
|
|
|||
|
效果:
|
|||
|
|
|||
|
20180301_1223.png
|
|||
|
|