Underscore是一個JavaScript實用庫,提供了一整套函數式編程的實用功能,可是沒有擴展任何JavaScript內置對象。它是這個問題的答案:「若是我在一個空白的HTML頁面前坐下, 並但願當即開始工做, 我須要什麼?「...它彌補了部分jQuery沒有實現的功能,同時又是Backbone.js必不可少的部分。css
Underscore提供了100多個函數,包括經常使用的: map, filter, invoke — 固然還有更多專業的輔助函數,如:函數綁定, JavaScript模板功能,建立快速索引, 強類型相等測試, 等等.html
template_.template(templateString, [settings])
將 JavaScript 模板編譯爲能夠用於頁面呈現的函數, 對於經過JSON數據源生成複雜的HTML並呈現出來的操做很是有用。 模板函數可使用 <%= … %>插入變量, 也能夠用<% … %>執行任意的 JavaScript 代碼。 若是您但願插入一個值, 並讓其進行HTML轉義,請使用<%- … %>。 當你要給模板函數賦值的時候,能夠傳遞一個含有與模板對應屬性的data對象 。 若是您要寫一個一次性的, 您能夠傳對象 data 做爲第二個參數給模板 template 來直接呈現, 這樣頁面會當即呈現而不是返回一個模板函數. 參數 settings 是一個哈希表包含任何能夠覆蓋的設置 _.templateSettings. jquery
var compiled = _.template("hello: <%= name %>"); compiled({name: 'moe'}); => "hello: moe" var template = _.template("<b><%- value %></b>"); template({value: '<script>'}); => "<b><script></b>"
您也能夠在JavaScript代碼中使用 print. 有時候這會比使用 <%= ... %> 更方便.正則表達式
var compiled = _.template("<% print('Hello ' + epithet); %>"); compiled({epithet: "stooge"}); => "Hello stooge"
若是ERB式的分隔符您不喜歡, 您能夠改變Underscore的模板設置, 使用別的符號來嵌入代碼.定義一個 interpolate 正則表達式來逐字匹配嵌入代碼的語句, 若是想插入轉義後的HTML代碼則須要定義一個 escape 正則表達式來匹配,還有一個 evaluate 正則表達式來匹配您想要直接一次性執行程序而不須要任何返回值的語句.您能夠定義或省略這三個的任意一個.例如, 要執行Mustache.js類型的模板:編程
_.templateSettings = { interpolate: /\{\{(.+?)\}\}/g }; var template = _.template("Hello {{ name }}!"); template({name: "Mustache"}); => "Hello Mustache!"
默認的, template 經過 with 語句來取得 data 全部的值. 固然, 您也能夠在 variable 設置裏指定一個變量名. 這樣能顯著提高模板的渲染速度.瀏覽器
_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
=> "Using 'with': no"
預編譯模板對調試不可重現的錯誤頗有幫助. 這是由於預編譯的模板能夠提供錯誤的代碼行號和堆棧跟蹤, 有些模板在客戶端(瀏覽器)上是不能經過編譯的 在編譯好的模板函數上, 有 source 屬性能夠提供簡單的預編譯功能.函數式編程
<script> JST.project = <%= _.template(jstText).source %>; </script>
另外本身作了一個經常使用的demo:函數
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>UnderscoreDemo</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="jquery.js"></script> <script src="../underscore.min.js"></script> </head> <body> </body> </html> <script id="historyTpl" type="text/template"> <%_.each(response, function(item) {%> <div class="historyItem"> <div class="historyDate"><%=item.date%></div> <%_.each(item.list, function(user) {%> <div class="userItem"> <img src="<%=user.icon%>"/><!----> <p><%=user.nick%></p> <p><%=user.prize%>天VIP會員</p> </div> <%});%> </div> <%});%> </script> <script> var response=[{"date":"Today","list":[{"uid":333222,"nick":"kitty","icon":"333.png","prize":30}]},{"date":"Yesterday","list":[{"uid":100077,"nick":"hello","icon":"333.png","prize":30}]},{"date":"2015-05-12","list":[{"uid":100077,"nick":"zealer9999","icon":"333.png","prize":30},{"uid":100034,"nick":"100034","icon":"333.png","prize":30}]}]; $("body").html( _.template($("#historyTpl").html(), response)); </script>