Mustache 是一個輕邏輯模板解析引擎,它的優點在於能夠應用在 Javascript、PHP、Python、Perl 等多種編程語言中。javascript
Mustache 的模板語法很簡單,就那麼幾個:
{{keyName}}
{{#keyName}} {{/keyName}}
{{^keyName}} {{/keyName}}
{{.}}
{{<partials}}
{{{keyName}}}
{{!comments}}html
傳統的寫後臺ajax過來的數據咱們會java
$.each(messages.reverse(), function(index, message) { $('#messageList').append( '<li><span class="list-title">' + message.userName + '</span>' + '<abbr class="list-timestamp" title="' + message.datePosted + '"></abbr>' + '<p class="list-text">' + message.messageText + '</p></li>'); } });
不停的進行字符串的拼接,那麼使用mustache後,咱們能夠web
<div id="wrap2"> <script id="myTemplate" type="x-tmpl-mustache"> {{#stooges}} <li> hello {{name}} </li> {{/stooges}} </script> </div>
<script> var data = { "company": "Apple", "address": { "street": "1 Infinite Loop Cupertino</br>", "city": "California ", "state": "CA ", "zip": "95014 " }, "product": ["Macbook ","iPhone ","iPod ","iPad "], "stooges": [ { "name": "Moe" }, { "name": "Larry" }, { "name": "Curly" }] } var tpl = $("#myTemplate").html(); var html = Mustache.to_html(tpl,data); $("#wrap2").append(html) </script>
{{}}就是 Mustache 的標示符,花括號裏的 keyName 表示鍵名,這句的做用是直接輸出與鍵名匹配的鍵值,例如:ajax
var tpl = '{{company}}'; var html = Mustache.render(tpl, data); //輸出: Apple
以#開始、以/結束表示區塊,它會根據當前上下文中的鍵值來對區塊進行一次或屢次渲染,例如改寫下 Demo 中的 tpl:編程
var tpl = '{{#stooges}} <li>hello {{name}}</li> {{/stooges}}'; var html = Mustache.render(tpl, data); //輸出: <li> hello Moe </li> <li> hello Larry </li> <li> hello Curly </li>
注意:若是{{#keyName}} {{/keyName}}中的 keyName 值爲 null, undefined, false;則不渲染輸出任何內容。
該語法與{{#keyName}} {{/keyName}}相似,不一樣在於它是當 keyName 值爲 null, undefined, false 時才渲染輸出該區塊內容。app
var tpl = {{^nothing}}沒找到 nothing 鍵名就會渲染這段{{/nothing}}; var html = Mustache.render(tpl, data); //輸出: 沒找到 nothing 鍵名就會渲染這段
{{keyName}}輸出會將等特殊字符轉譯,若是想保持內容原樣輸出能夠使用{{{}}},例如:編程語言
var tpl = '{{#address}} <p>{{{street}}}</p> {{/address}}' //輸出: <p>1 Infinite Loop Cupertino</br></p>
!表示註釋,註釋後不會渲染輸出任何內容。oop
{{!這裏是註釋}} //輸出:
參考資料url