最近看了下 underscore.js ,看到裏面有個 template 的方法,小使了一下,感受挺不錯的,以爲能知足我平常工做的需求了,並且使用起來也簡單容易,具體用法能夠 參考這裏 。還有, underscore.js 是個不錯的東西呀,裏面有不少很實用的方法,均可以順手拿來使用,省了很多功夫呢。:)javascript
<script type="text/template" id="tpl"> <% _.each(datas, function (item) { %> <div class="outer"> <%= item.title %> - <%= item.url %> - <%= item.film %> </div> <% }); %> </script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script> <script type="text/javascript"> var datas = [ { title: '標題1', url: 'http://www.baidu.com', film: '電影名稱1' }, { title: '標題2', url: 'http://www.baidu.com', film: '電影名稱2' }, { title: '標題3', url: 'http://www.baidu.com', film: '電影名稱3' }, { title: '標題4', url: 'http://www.baidu.com', film: '電影名稱4' }, { title: '標題5', url: 'http://www.baidu.com', film: '電影名稱5' } ]; $('body').html( _.template($('#tpl').html(), datas) ); </script>
具體關於underscore的模型引擎,官方介紹以下:html
template_.template(templateString, [settings])
將 JavaScript 模板編譯爲能夠用於頁面呈現的函數, 對於經過JSON數據源生成複雜的HTML並呈現出來的操做很是有用。 模板函數可使用 <%= … %>插入變量, 也能夠用<% … %>執行任意的 JavaScript 代碼。 若是您但願插入一個值, 並讓其進行HTML轉義,請使用<%- … %>。 當你要給模板函數賦值的時候,能夠傳遞一個含有與模板對應屬性的data對象 。 若是您要寫一個一次性的, 您能夠傳對象 data 做爲第二個參數給模板 template 來直接呈現, 這樣頁面會當即呈現而不是返回一個模板函數. 參數 settings 是一個哈希表包含任何能夠覆蓋的設置 _.templateSettings.java
var compiled = _.template("hello: <%= name %>"); compiled({name: 'moe'}); => "hello: moe" var template = _.template("<b><%- value %></b>"); template({value: '<script>'}); => "<b><script></b>"
您也能夠在JavaScript代碼中使用 print. 有時候這會比使用 <%= ... %> 更方便.jquery
var compiled = _.template("<% print('Hello ' + epithet); %>"); compiled({epithet: "stooge"}); => "Hello stooge"
若是ERB式的分隔符您不喜歡, 您能夠改變Underscore的模板設置, 使用別的符號來嵌入代碼.定義一個 interpolate 正則表達式來逐字匹配嵌入代碼的語句, 若是想插入轉義後的HTML代碼則須要定義一個 escape 正則表達式來匹配,還有一個 evaluate 正則表達式來匹配您想要直接一次性執行程序而不須要任何返回值的語句.您能夠定義或省略這三個的任意一個.例如, 要執行Mustache.js類型的模板:git
_.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; var template = _.template("Hello {{ name }}!"); template({name: "Mustache"}); => "Hello Mustache!"
默認的, template 經過 with 語句來取得 data 全部的值. 固然, 您也能夠在 variable 設置裏指定一個變量名. 這樣能顯著提高模板的渲染速度.github
_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'}); => "Using 'with': no"
預編譯模板對調試不可重現的錯誤頗有幫助. 這是由於預編譯的模板能夠提供錯誤的代碼行號和堆棧跟蹤, 有些模板在客戶端(瀏覽器)上是不能經過編譯的 在編譯好的模板函數上, 有 source 屬性能夠提供簡單的預編譯功能.ajax
<script> JST.project = <%= _.template(jstText).source %>; </script>