参考资料:https://github.com/aui/artTemplate
http://aui.github.io/art-template/zh-cn/
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<div id="content">div>
<script src="../template.js">script>
<script id="test" type="text/html">
<h1>{{title}}</h1>
<ul>
{{each list as value i}}
<li>索引 {{i + 1}} :{{value}}</li>
{{/each}}
</ul>
script>
<script>
var data = {
title: '基本例子',
isAdmin: true,
list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']
};
var html = template('test', data);
document.getElementById('content').innerHTML = html;
script>
body>
html>
由于开发过程中不会将模板和js写在页面内,所以,我们会单独写一个模板页,并将其引入到页面内,进行模板替换,如果是这样的话,我们就需要对调用template的方法进行一些小小的调整
模板页html如下
{{if isAdmin}}
<h1>{{title}}h1>
<ul>
{{each list as value i}}
<li>索引 {{i + 1}} :{{value}}li>
{{/each}}
ul>
{{/if}}
js代码如下
<script>
var obj = {
title: '模板页获取例子',
isAdmin: true,
list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']
};
var html=$.get('template.html',function (data) {
var render = template.compile(data);
var str = render(obj);
document.getElementById('content').innerHTML = str;
})
</script>
这里使用jquery的get方法获取模板页,这时候就不能使用template()方法进行模板替换了,必须使用template.compile()及render()进行模板替换才行。
数据:
inputData = {
"flag": true,
"orderArray": [{
"id": "1",
"name": "张三", //用户名
"identity": [ //证件类型
{
"id_type": [{
"id": 1,
"name": "身份证"
}],
"id": "110105199408286510"
}
],
"phone": "15210329866", //手机号
"date_of_birth": "19940828", //出声日期
"address": "北京", //地址
}, {
"id": "2",
"name": "赵四",
"identity": [{
"id_type": [{
"id": 1,
"name": "身份证"
}],
"id": "110105199508286510"
}],
"phone": "15210329877",
"date_of_birth": "19950828",
"address": "北京",
}, {
"id": "3",
"name": "王五",
"identity": [{
"id_type": [{
"id": 2,
"name": "护照"
}],
"id": "G49331247"
}],
"phone": "15210329877",
"date_of_birth": "20010124",
"address": "上海",
}]
};
模板代码
<script type="text/html" id="test">
{{if flag}}
{{each orderArray as value}}
<tr>
<td>{{value.name}}</td>
{{each value.identity as v}}
{{each v.id_type as vi}}
<td>{{vi.name}}</td>
{{/each}}
<td>{{v.id}}</td>
{{/each}}
<td>{{value.phone}}</td>
<td>{{value.date_of_birth}}</td>
</tr>
{{/each}}
{{/if}}
</script>