1.首先引入jQuery文件和template.js文件:
<script src='jQuery-2.1.4.min.js'></script>
<script src='template.js'></script>
2.渲染表格数据为json格式:
var data1 = {
headname:['星期','年','月','日'],
list : [{"tags1":'英语',
"tags2":'语文',
"tags3":'数学',
"tags4":'政治'
},
{
"tags1":'地理',
"tags2":'体育',
"tags3":'英语',
"tags4":'历史'
}]
};
3.渲染代码如下:
<script>
$(function(){
var data1 = {
headname:['星期','年','月','日'],
list : [{"tags1":'英语',
"tags2":'语文',
"tags3":'数学',
"tags4":'政治'
},
{
"tags1":'地理',
"tags2":'体育',
"tags3":'英语',
"tags4":'历史'
}]
};
var html = template("art3",data1);
$("#content").append(html);
})
</script>
<script id="art3" type="text/html">
<div>
<table border=1>
{{include 'art5' $value}}
</table>
</div>
</script>
<script id="art5" type="text/html">
<thead>
<tr>
{{each headname}}
<th>{{$value}}</th>
{{/each}}
</tr>
</thead>
<tbody>
{{each list}}
<tr>
<td>{{$value.tags1}}</td>
<td>{{$value.tags2}}</td>
<td>{{$value.tags3}}</td>
<td>{{$value.tags4}}</td>
</tr>
{{/each}}
</tbody>
</script>
上述代码可以简化为:
<script id="art3" type="text/html">
<table border=1>
<thead>
<tr>
{{each headname}}
<th>{{$value}}</th>
{{/each}}
</tr>
</thead>
<tbody>
{{each list}}
<tr>
<td>{{$value.tags1}}</td>
<td>{{$value.tags2}}</td>
<td>{{$value.tags3}}</td>
<td>{{$value.tags4}}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>