首页 > 代码库 > mustache.js使用基本(三)

mustache.js使用基本(三)

作者:zccst

本节要点是子模块(partials)和分隔符(delimiter)等

1,子模块(partials)

/*
{{>partials}}以>开始表示子模块,如{{> address}};

当结构比较复杂时,我们可以使用该语法将复杂的结构拆分成几个小的子模块,例如:
*/

var data =http://www.mamicode.com/ {
    "company": "Apple",
    "address": {
        "street": "1 Infinite Loop Cupertino</br>",
        "city": "California ",
        "state": "CA ",
        "zip": "95014 "
    },
    "product": ["Macbook ","iPhone ","iPod ","iPad "]
}

//主模板
var tpl = "<h1>{{company}}</h1> <ul>{{>address}}</ul>";

//子模板写法1:定义一个子模块对象。里面放子模板。
var partials = {
    address: "{{#address}}<li>{{street}}</li><li>{{city}}</li><li>{{state}}</li><li>{{zip}}</li>{{/address}}"
}
var html = Mustache.render(tpl, data, partials);


//子模板写法2:直接写在第三个参数里
var html = Mustache.render(tpl, data, {address: "{{#address}}<li>{{street}}</li><li>{{city}}</li><li>{{state}}</li><li>{{zip}}</li>{{/address}}"});
document.getElementById("target").innerHTML = html;

再举一例:

var view = {
    name: "Joe",
    winnings: {
        value: 1000
    }
};
var template = "Welcome, {{name}}! {{#winnings}} {{>winnings}}{{/winnings}} "
var partials = {
    winnings: "You just won ${{value}}"
};
var output = Mustache.to_html(template, view, partials);
document.getElementById("target").innerHTML = output;

输出结果是:

Welcome, Joe! You just won $1000

 

 

2,分隔符(delimiter)

(1)写法1:默认的标签风格

* {{ default_tags }}
{{=<% %>=}}

(2)写法2:使用ERB风格
* <% erb_style_tags %>
<%={{ }}=%>

(3)写法3:
* {{ default_tags_again }}

 

3,预解析或缓存parse

mustache.js会在第一次读模板时缓存,第二次可加快速度,如果需要

Mustache.pars(template);

Mustache.render(template, view);

 

 

4,对应的插件

有jQuery,MooTools,Dojo,YUI,qooxdoo。可以使用Rake来built。

 

5,测试(单元测试和整体测试)