微信小程序 Mustache语法详解

最近微信小程序非常火,对于前端开发的程序员是个利好的消息,这里主要记录下微信小程序  Mustache语法。

小程序开发的wxml里,用到了Mustache语法。所以,非常有必要把Mustache研究下。

什么是Mustache?Mustache是一个logic-less(轻逻辑)模板解析引擎,它是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,通常是标准的HTML文档。比如小程序的wxml中的代码:

{{userInfo.nickName}},这里的{{ }}就是Mustache的语法。

1、Mustache的模板语法很简单,就那么几个:

{{keyName}}

{{{keyName}}}

{{#keyName}} {{/keyName}}

{{^keyName}} {{/keyName}}

{{.}}

{{!comments}}

{{>partials}}

1、{{keyName}}

⑴ 简单的变量替换:{{name}}

var data = { "name": "weChat" };

Mustache.render("{{name}} is excellent.",data);

返回 weChat is excellent.

⑵ 变量含有html的代码,如:

、等而不想转义,可以在用{{&name}}

 

vardata = {

"name":"

weChat

"

};

varoutput = Mustache.render("{{&name}} is excellent.", data);

console.log(output);

返回:

weChat

is excellent.

去掉"&"的返回是转义为:

weChat

is excellent.

另外,你也可以用{{{ }}}代替{{&}}。

⑶ 若是对象,还能声明其属性

vardata = {

"name": {

"first":"Chen",

"last":"Jackson"

},

"age": 18

};

varoutput = Mustache.render(

"name:{{name.first}} {{name.last}},age:{{age}}", data);

console.log(output);

返回:name:Chen Jackson,age:18

2、{{#keyName}} {{/keyName}}

以#开始、以/结束表示区块,它会根据当前上下文中的键值来对区块进行一次或多次渲染。它的功能很强大,有类似if、foreach的功能。vardata = {

"stooges": [ {

"name":"Moe"

}, {

"name":"Larry"

}, {

"name":"Curly"

} ]

};

varoutput = Mustache.render("{{#stooges}}{{name}}{{/stooges}}",

data);

console.log(output);

返回:Moe

Larry

Curly

3、{{^keyName}} {{/keyName}}

该语法与{{#keyName}} {{/keyName}}类似,不同在于它是当keyName值为null, undefined, false时才渲染输出该区块内容。比如

vardata = {

"name":"

weChat

"

};

vartpl = ‘{{^nothing}}没找到 nothing 键名就会渲染这段{{/nothing}}';

varoutput = Mustache.render(tpl, data);

返回:没找到 nothing 键名就会渲染这段

4、{{.}}

{{.}}表示枚举,可以循环输出整个数组,例如:

vardata = {

"product": ["Macbook ","iPhone ","iPod ","iPad "]

}

vartpl ='{{#product}}

{{.}}

{{/product}}';

varhtml = Mustache.render(tpl, data);

返回:

Macbook

iPhone

iPod

iPad

5、{{!  }}表示注释

6、{{>partials}}

 

参考文章:http://www.open-open.com/lib/view/open1416792564461.html

http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/

http://mustache.github.com/mustache.5.html

http://ued.xinyou.com/2012/07/mustache_5_document.html

来自:http://www.iinterest.net/2012/09/12/web-template-engine-mustache/



作者:大宝来巡山
链接:https://www.jianshu.com/p/ca2659317d02
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on   byd张小伟  阅读(428)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示