Underscore 是一個非常實用的 JavaScript 函式庫,在不擴充任何原生物件的情況下,提供了大量實用功能。無論你是寫一小段 JS,還是打造大型 HTML5 應用,它都能幫上忙。目前它已被廣泛採用——例如 backbone.js 唯一強依賴的庫就是 underscore.js。
今天主要討論 Underscore 的前端模板功能。它的模板概念與一般 JS 前端模板一致,但對資料的處理更加便利。下面寫了個小範例供大家參考:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Underscore</title>
<script src="jquery.js"></script>
<script src="underscore.js"></script>
</head>
<body>
</body>
</html>
<!-- ace-template demo -->
<script id="t2" type="text/template">
<%_.each(datas, function(item) {%>
<div class="outer">
<div class="title">
<span ><%=item.film%></span>
</div>
<ul class="ul">
<%_.each(datas, function(item) {%>
<li>
<a href="<%=item.url%>">【<%=item.title%>】</a>
</li>
<%});%>
</ul>
</div>
<%});%>
</script>
<!-- 數據 -->
<script>
var datas = [
{ title: "一九四二", url: "https://www.jb51.net", film:"電影1" },
{ title: "少年派的漂流", url: "https://www.jb51.net", film:"電影2" },
{ title: "教父", url: "https://www.jb51.net", film:"電影3" },
{ title: "肖申克的救贖", url: "https://www.jb51.net", film:"電影4" },
{ title: "3d2012", url: "https://www.jb51.net", film:"電影5" }
];
$("body").html( _.template($("#t2").html(), datas));
</script>
核心就一句:_.template($("#t2").html(), datas)。模板裡用 <% %> 包 JavaScript 邏輯(如 _.each 迴圈),用 <%= %> 輸出變數值,最後把資料灌進去,HTML 就自動生成了。這種「模板與資料分離」的寫法,讓動態渲染列表變得清爽又直觀。
以下再補上一點交互效果,示範如何搭配 jQuery 做下拉收合:
$('.ul').hide();
$('.ul>li:last-child').addClass('last-li');
$('body>div:first-child>ul').show();
$('.title').click(function(){ $(this).siblings().toggle(); });