作者:zccst
本文记录基本使用二,主要讲sections。
{{#person}} {{/person}}
1,当person是null, undefined, false, 0, NaN, "", [], 空列表时不渲染
2,当person不空时渲染一次或多次。如果其中某一些为空,则改行略过,其他行正常。
var template = '{{#beatles}}* {{name}} <br/>{{/beatles}}';
var obj = {
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
console.log(this,this===obj);//结论:由于循环的是beatles,所以this指向的是beatles,而不是obj。
return this.firstName + " " + this.lastName;
}
}
var rendered = Mustache.render(template,obj);
$('#target').html(rendered);
3,相反,就是输出空,仅在 section标签是null, undefined, false, 空list时
用{{^section}} 替换 {{#section}}
var template = '{{#repos}}<b>{{name}}</b>{{/repos}} {{^repos}}No repos :({{/repos}}';
var obj = {
"repos": []
}
var rendered = Mustache.render(template,obj);
$('#target1').html(rendered);
4,特殊情况:数组,里面每一项都是字符串时,可以用点代替
var template = '{{#musketeers}}* {{.}} <br/>{{/musketeers}}';
var obj = {
"musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}
var rendered = Mustache.render(template,obj);
$('#target').html(rendered);
5,function
var template = '{{#bold}}Hi {{name}}.{{/bold}}';
var obj = {
"name": "Tater",
"bold": function () {
return function (text, render) {
return "<b>" + render(text) + "</b>";//text是Hi {{name}}.render是原生函数
}
}
}
var rendered = Mustache.render(template,obj);
$('#target').html(rendered);
<div id="target">Loading...</div>