一、开篇
下载underscode.js
二、使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="underscore.js"></script>
<script src="jq.js"></script>
<title>Document</title>
</head>
<body>
<ul id="element"></ul>
<!-- 定义模板,将模板内容放到一个script标签中 -->
<script type="text/template" id="tpl">
<% for(var i = 0; i < data.list.length; i++) { %>
<% var item = list[i] %>
<li>
<span><%=item.firstName%> <%=item.lastName%></span>
<span><%-item.city%></span>
</li>
<% } %>
</script>
</body>
</html>
<script>
// 获取渲染元素和模板内容
var element = $('#element'),
tpl = $('#tpl').html();
// 创建数据, 这些数据可能是你从服务器获取的
var data = {
list: [
{firstName: 'dirk', lastName: 'San', city: 'Shanghai'},
{firstName: 'Li', lastName: 'Si', city: 'sz'},
{firstName: 'Wang', lastName: 'Wu', city: 'Guangzhou'},
{firstName: 'Zhao', lastName: 'Liu', city: 'Shenzhen'}
]
}
// 解析模板, 返回解析后的内容
var render = _.template(tpl);
var html = render(data);
// 将解析后的内容填充到渲染元素
element.html(html);
</script>
三、效果