mustache.js的使用說明

Mustache 是個不錯的js模板引擎,源碼:https://github.com/janl/mustache.js

mustache的一些說明:http://mustache.github.com/mustache.5.html

下面是自己總結的一些小說明

1、簡單的變量替換{{name}}

     eg:var data={"name":"Jhon"};
            var output= Mustache.render("{{name}} is awsome",data);
            console.log(output);//Jhon is awsome.
2、若是變量中含有html代碼,而又不想轉義的,在變量前面加上&即可。{{&name}}
3、變量是對象時,還可以聲明其屬性:
    eg:var data = { "name": {
                              "first":"Willy",
                              "last":"John"
                         },
               "age":"18"};

            var output=Mustache.render("{{name.first}} {{name.last}} is {{age}}  years old.",data);
            console.log(output);//Willy Jhon is 18 years old.
4、{{#param}}標籤的功能很強大,有if判斷、foreach的功能
     eg1://判斷
   
 var data = {
              "nothin":true
           };
            var output = Mustache.render(
                    "Shown.{{#nothin}}Never shown!{{/nothin}}", data);
             console.log(output);//Shown.Never shown!

eg2:迭代
  var data = {
     "stooges":[{ "name" : "Moe" },
                   { "name" : "Larry"},
                   {"name" : "Curly"}
                   ]
        };var output = Mustache.render("{{#stooges}}       {{name}}       {{/stooges}}",data);
console.log(output);//     Moe              Larry              Curly   

     
      若迭代的是數組,還可以通過{{.}}來調換每個元素
      eg3://數組迭代
     
 var data = {
             "musketeers":[ "Athos", "Aramis", "Porthos", "D","Artagnan" ]
         };
        var output = Mustache.render("{{#musketeers}}   * {{.}}     {{/musketeers}}",
                 data);
         console.log(output);// * Athos * Aramis * Porthos * D * Artagnan


5、迭代輸出還可以是一個function返回的結果:
var data = {
            "beatles" : [ {
                "firstName" : "John",
               "lastName" : "Lennon"
            }, {
                "firstName" : "Paul",
                "lastName" : "McCartney"
            } ],
            "name" : function() {
                return this.firstName + " " + this.lastName;
            }
         };
var output = Mustache.render("{{#beatles}} *{{name}}        {{/beatles}}", data);
console.log(output);//*John Lennon *Paul McCartney

6、{{^}}與{{#}}相反,若變量是null、undefined、 false、和空數組則執行相應操作,相當於提供了一個錯誤處理機制
{{#repo}}
  <b>{{name}}</b>
{{/repo}}
{{^repo}}
  No repos :(
{{/repo}}

7、 {{!  }}註釋
8、包含
base.mustache:
<h2>Names</h2>
{{#names}}

 
 {{> user}}
{{/names}}
user.mustache:
<strong>{{name}}</strong>    

上述代碼等價於:
<h2>Names</h2>
{{#names}}
  <strong>{{name}}</strong>
{{/names}}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章