关于 underscore 中模板引擎的应用演示样例

时间:2023-11-22 13:34:32

//关于 underscore 中模板引擎的应用演示样例
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>关于 underscore 中模板引擎的应用演示样例</title>
</head>
<body>
<ul id="test"></ul>

<script type="text/template" id="tpl">
<% for(var i = 0; i < list.length; i++) { %>
<% var item = list[i] %>
<li>
<span><%=item.firstName%> <%=item.lastName%></span>
<span><%-item.city%></span>
</li>
<% } %>
</script>
<script src="sea.js"></script>
<script>
seajs.config({
paths: {
'baiducdn': 'http://libs.baidu.com',
'360cdn': 'http://libs.useso.com/',
'freecdn': 'http://libs.cncdn.cn/',
'sinacdn': 'http://lib.sinaapp.com/',
},
alias: {
'jquery': 'baiducdn/jquery/2.0.3/jquery.min.js',
'backbone': 'baiducdn/backbone/0.9.2/backbone-min.js',
'underscore': 'baiducdn/underscore/1.3.3/underscore-min.js',
},
});
seajs.use(['jquery', 'underscore'], function(){
var testObj = $('#test'),
tpl = $('#tpl').html();

//准备数据,能够通过JSON来自server
var data = {
list: [
{firstName: 'Li', lastName: 'Yunlong', city: '济南'},
{firstName: 'Wang', lastName: 'Yunlong', city: '北京'},
]
};
var html = _.template(tpl, data);//解析模板
testObj.html(html);
});

</script>
</body>
</html>