现在有许多javascript模板引擎和服务器端的freemarker那些很像,定义模板像下面:
<textarea id="template" style="display:none">
<strong>{$T.name} : {$T.list_id}</strong>
<table>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>邮箱</th>
</tr>
{#foreach $T.table as record}
<tr>
<td>{$T.record.id}</td>
<td>{$T.record.name}</td>
<td>{$T.record.age}</td>
<td>{$T.record.mail}</td>
</tr>
{#/for}
</table>
</textarea>
感觉对html改动较大,pure就不一样了,对美工做的html影响很小。看下面一个例子:
<html>
<head>
<title>PURE Unobtrusive Rendering Engine</title>
<script src="../libs/jquery.js"></script>
<script src="../libs/pure.js"></script>
<style>
.even td { background : #DDD }
.odd td { background : #FFF }
</style>
</head>
<body>
<div style="width:100%; height: 288px; overflow: auto;">
<!-- HTML 模板 -->
<table id="mytb1" class="rc_bk" width="100%" border="0" cellspacing="0" cellpadding="0">
<tr onmouseover="$(this).addClass('highlight');" onmouseout="$(this).removeClass('highlight');">
<td width="25%" class="rownum rightborder"></td>
<td width="25%" class="company rightborder"></td>
<td width="25%" class="amount rightborder"></td>
<td width="25%" class="increment"></td>
</tr>
</table>
</div>
<script>
// the JSON data we want to render
var data = {"rows":[{"company":'adobe',"increment":1552,"amount":14810},{"company":'google',"increment":-541,"amount":7470},{"company":'bea',"increment":865,"amount":6700},{"company":'red',"increment":756,"amount":6643},{"company":'abc',"increment":180,"amount":6239},{"company":'jboss',"increment":609,"amount":6219},{"company":'中华',"increment":-1116,"amount":6036},{"company":'no',"increment":95,"amount":5593},{"company":'sun',"increment":-143,"amount":4660},{"company":'test',"increment":-357,"amount":4541},{"company":'oracle',"increment":-181,"amount":4327},{"company":'dark',"increment":-393,"amount":3252},{"company":'ibm',"increment":-567,"amount":3147}]};
var directive = {
'tr' : { //trigger a loop
'row<-rows' : { // loop on the property animals in the JSON
'td.rownum': function(arg){if(arg.pos == arg.row.items.length - 1) return ''; return arg.pos + 1;},
'td.company': '#{row.company}',
'td.amount': '#{row.amount}',
'td.increment': '#{row.increment}',
'@class+':function(arg){ // add(+) the return value of the function to the class
return (arg.pos % 2 == 0) ? ' even' : ' odd';
}
}
}
};
// run the rendering
$('#mytb1').render( data, directive );
</script>
</body>
</html>
可以不刷新页面把ajax请求的数据多次render同一个模板。
开源项目,功能完善,示例丰富,把事情变简单了。