标签:io os ar 使用 for sp on art cti
看了Mustache的github,学学其中的语法,做个笔记
1.简单的变量替换:{{name}}
var data = { "name": "Willy" }; Mustache.render("{{name}} is awesome.",data);
返回结果 Willy is awesome.
2.如果变量含有html的代码的,例如:<br>、<tr>等等而不想转义可以在用{{&name}}
var data = { "name" : "<br>Willy<br>" }; var output = Mustache.render("{{&name}} is awesome.", data); console.log(output);
结果:<br>Willy<br> is awesome.
去掉"&"的结果是转义为:<br>Willy<br> is awesome.(默认将"<"和">"转义)
3.如果是对象,还能解释其属性
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
4.{{#param}}这个标签很强大,有if判断、forEach的功能。
var data = { "nothin":true }; var output = Mustache.render( "Shown.{{#nothin}}Never shown!{{/nothin}}", data); console.log(output);
如果nothin是空或者null,或者是false都会输出Shown.相反则是Shown.Never shown!。
5.迭代
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>
6.如果迭代的是数组,还可以用{{.}}来替代每个元素
var data = { "musketeers" : [ "Athos", "Aramis", "Porthos", "D‘Artagnan" ] }; var output = Mustache.render("{{#musketeers}}* {{&.}}{{/musketeers}}", data); console.log(output);
输出:* Athos
* Aramis
* Porthos
* D‘Artagnan
7.迭代输出的还可以是一个function返回的结果,function可以读取当前变量的上下文来获取其他属性执行其他操作
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);
输出: *John Lennon
*Paul McCartney
*George Harrison
*Ringo Starr
8:方法里面可以再执行变量中的表达式
var data = { "name" : "{{age}}" + "Tater", "bold" : function() { return function(text, render) { console.log(text); return "<b>" + render(text) + "</b>"; }; }, "age" : 18 }; var output = Mustache.render("{{#bold}}Hi {{name}}.{{/bold}}", data); console.log(output);
输出结果:
Hi {{age}}Tater.
<b>Hi 18Tater.</b>
9.{{^}}与{{#}}相反,如果变量是null、undefined、 false、和空数组讲输出结果
10.{{! }}注释
标签:io os ar 使用 for sp on art cti
原文地址:http://my.oschina.net/bluefrankey/blog/335155