1. 程式人生 > >學習筆記《Mustache》模板

學習筆記《Mustache》模板

.com last 前後端 好的 .sh fun http some lar

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

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

Mustache 功能非常經典,這裏就能全部羅列出來:

變量

{{person}}

帶有HTML的變量

{{{person}}}

循環

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

數組循環的時候可以用.作為下標

{ "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

學習筆記《Mustache》模板