项目过程中,经常有时候后端返回的数据需要转化,但是使用模板引擎不知道怎么转,因此有这笔记。标红色是定义和执行关键
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>demo</title>
<style>
table{border-collapse:collapse ;}
td,th{border: red solid 1px; width: 80px; text-align: left;}
</style>
</head>
<body>
<div class="studentWrapp">
<script id="studentTp" type="text/html">
{{each studentList sl}}
<fieldset>
<legend>{{sl.clas | clasFilter}}</legend>
<table >
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
{{each sl.arr slarr}}
<tr>
<td>{{slarr.name}}</td>
<td>{{slarr.age}}</td>
</tr>
{{/each}}
</tbody>
</table>
</fieldset>
{{/each}}
</script>
</div>
<script src="lib/jquery-3.2.1.min.js"></script>
<script src="lib/template-web.js" ></script>
<script>
//模拟后端数据服务
function getSudent(){
var result=[
{
clas:1,
arr:[{id:201701,name:'丁少',age:20},{id:201703,name:'张三',age:16}]
},
{
clas:2,
arr:[{id:201702,name:'王新',age:21},{id:201704,name:'李四',age:18}]
}
];
return result;
}
//过滤器
template.defaults.imports.clasFilter=function (clas) {
var temp='未知';
if(clas==1){
temp='一年级'
}else if(clas==2){
temp='二年级'
}
return temp;
}
//渲染至dom
var studentList=getSudent();
var tempData={studentList:studentList};
$('.studentWrapp').html(template('studentTp', tempData));
</script>
</body>
</html>