學習筆記《Mustache》模板

Mustache 是一款經典的前端模板引擎,在先後端分離的技術架構下面,前端模板引擎是一種能夠被考慮的技術選型,隨着重型框架(AngularJS、ReactJS、Vue)的流行,前端的模板技術已經成爲了某種形式上的標配,Mustache 的價值在於其穩定和經典:
主頁:https://github.com/janl/mustache.js/
文檔:https://mustache.github.io/mustache.5.htmlhtml

Mustache 在使用的時候,會在頁面上出現 {{person}} 這樣的標籤,載入的時候會顯示出來,而後當即被替換掉,這個對於頁面的呈現是不夠友好的,這是我在使用的過程當中遇到的一個痛點。前端

Mustache 功能很是經典,這裏就能所有羅列出來:git

變量

{{person}}

帶有HTML的變量

{{{person}}}

循環

{{#persons}} ...... {{/persons}}

數組循環的時候能夠用.做爲下標github

{ "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] } {{#musketeers}} {{.}} {{/musketeers}}

對象

正常使用:
{ "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP" }
{{name.first}} {{name.last}}
{{age}}後端

循環使用:
{ "stooges": [ { "name": "Moe" }, { "name": "Larry" }, { "name": "Curly" } ] }
{{#stooges}}
{{name}}
{{/stooges}}數組

if else

{{#person}}
......
{{/person}}
{{^person}}
......
{{/person}}緩存

布爾判斷

和前面循環的語法是同樣的,取決於變量是不是一個數組
{{#person}}
......
{{/person}}架構

數組的布爾判斷

當一個數組沒有任何值的時候,可能會但願不作任何的顯示,因此須要這個判斷
{{#persons.length}}
......
{{/persons.length}}框架

Lambdas

遇到和前面的循環和布爾表達式同樣,取決於參數的類型
{{#person}}
{{name}} is awesome.
{{/person}}前後端分離

{ "name": "Willy", "person": function() { return function(text, render) { return "<b>" + render(text) + "</b>" } } }

輸出
<b>Willy is awesome.</b>

註釋

這玩意兒有啥用呢?
{{! ignore me }}

Trick

在作<tr></tr>的循環輸出的時候,須要使用相似這樣的形式(感受這就是BUG啊,或者是HTML標準的問題?):
``
<tr> <td>{{name}}</td> <td>{{age}}</td> </tr>

兩個核心方法

Mustache.parse(template);
Mustache.render(template, obj);

由於動態載入到 HTML 上的事件或者元素會丟失,因此我封裝了一個對模板的緩存:

$(templateKey).each(function(i){ templateExist = false; $(templateArray).each(function(index){ if (templateArray[index][0] == templateKey+i) { templateExist = true; template = templateArray[index][1]; } }) if (templateExist != true) { template = $(this).html(); templateArray.push([templateKey+i, template]); } Mustache.parse(template); $(this).html(Mustache.render(template, item.data)).show(); if (callbackFunction) { callbackFunction(item.data); }; })

順便簡單學習了一下 Handlebars,這款也很是的知名,而且是基於 Mustache 的模板引擎:
Handlebars:http://handlebarsjs.com/

若是你但願像傳統模板引擎同樣能夠有函數和參數處理等等的功能,那麼 Mustache 就不是好的選擇,可是再複雜了往上走的話,就不如選用 Vue 了

連接:https://www.jianshu.com/p/7f1cecdc27e1

相關文章
相關標籤/搜索