首先先定义一个type="x-tmpl-mustache"的模板脚本并给与一个id
<script id="paginateTemplate" type="x-tmpl-mustache">
<p> Hello,{{name}}</p>
</script>
其次再在html页面中定义一个div容器,并给一个id名
<div id="context"></div>
最后再在</body>前写javascript脚本做模板渲染
<script type="text/javascript">
var data = { "phone": "iphone" }
var Template = $('#paginateTemplate').html();
var rendered = Mustache.render(Template,data);
$('#context').html(rendered);
</script>
var data = {
"name" : {
"first" : "Chen",
"last" : "Jackson"
},
"age" : 18
};
var output = Mustache.render(
"name:{{name.first}} {{name.last}},age:{{age}}", data);
console.log(output);
结果:name:Chen Jackson,age:18
var data = {
"nothin":true
};
var output = Mustache.render(
"Shown.{{#nothin}}Never shown!{{/nothin}}", data);
console.log(output);
结果:如果nothin是空或者null,或者是false都会输出Shown.相反则是Shown.Never shown!。
下面是迭代功能的使用:
var data = {
"stooges" : [ {
"name" : "Moe"
}, {
"name" : "Larry"
}, {
"name" : "Curly"
} ]
};
var output = Mustache.render("{{#stooges}}<b>{{name}}</b>{{/stooges}}",
data);
console.log(output);
输出:<b>Moe</b>
<b>Larry</b>
<b>Curly</b>
var data = {
"musketeers" : [ "Athos", "Aramis", "Porthos", "D'Artagnan" ]
};
var output = Mustache.render("{{#musketeers}}* {{&.}}{{/musketeers}}",data);
console.log(output);
输出:
* Athos
* Aramis
* Porthos
* D’Artagnan
var data = {
"beatles" : [ {
"firstName" : "John",
"lastName" : "Lennon"
}, {
"firstName" : "Paul",
"lastName" : "McCartney"
}, {
"firstName" : "George",
"lastName" : "Harrison"
}, {
"firstName" : "Ringo",
"lastName" : "Starr"
} ],
"name" : function() {
return this.firstName + " " + this.lastName;
}
};
var output = Mustache
.render("{{#beatles}} *{{name}}{{/beatles}}", data);
console.log(output);
9.{{^}}与{{#}}相反,如果变量是null、undefined、 false、和空数组讲输出结果
10.{{! }}注释