模板的用法
- 引入模板
<script src="template.js"></script>
- 创建模板(原生语法)
<div id="div"></div>
<script type="text/template" id="tpl">
<table id="table">
<thead>
<% for(var i = 0; i< headers.length; i++){ %>
<th><%= headers[i] %></th>
<% } %>
</thead>
<tbody>
<% for(var i = 0;i< list.length; i++){ %>
<tr>
<% for(var k in list[i]){ %>
<td><%= list[i][k] %></td>
<% } %>
</tr>
<% } %>
</tbody>
</table>
</script>
* 原生语法的语法规则
<% title %>
<%= value %>
* 简洁语法
<div id="div"></div>
<script type="text/template" id="tpl">
<table id="table">
<thead>
{{ each headers }}
<th>{{ $value }}</th>
{{ /each }}
</thead>
<tbody>
{{ each list as item index }}
<tr>
{{ each item }}
<td>{{ $value }}</td>
{{ /each }}
</tr>
{{ /each }}
</tbody>
</table>
</script>
* 简洁语法的语法规则
{{ each }}
{{ $value }}
{{ /each }}
* 模板数据一般是从后台获取
var data = [
{name:"张三",age:19,gender:"男"},
{name:"李四",age:22,gender:"男"},
{name:"小明",age:31,gender:"男"},
{name:"小红",age:18,gender:"女"},
{name:"小白",age:16,gender:"女"}
];
* 将数组数据变成对象数据
var obj = {
headers:["name","age","gender"],
list:data
};
* 渲染模板内容
var html = template("tpl",obj);
template.compile(source, options)
source:必传,渲染模板的内容。