swift 之 mustache模板引擎
用法:
-
Variable Tags
-
{{name}}
用来渲染值namedatas: let data = ["value": "test"] ----------- template: {{value}} a lession ----------- rendering: test a lession
-
-
Section Tags
-
{{#items}}...{{/items}}
执行条件语句,枚举出里面的对象- 按需渲染数据
- 遍历数据
- 获取里面的每一项
如果
{{value}}...{{/value}}
中的value错误的(下面的),那么将不会被渲染:
1. 缺少值
2. false
3. 0
4. 字符串
5. 空集合
6. 为NSNull如果value 是集合的话
datas: [ "friends": [ [ "name": "Hulk Hogan" ], [ "name": "Albert Einstein" ], [ "name": "Tom Selleck" ], ] ] ------------- template: {{# friends }} - {{ name }} {{/ friends }} ------------- rendering: - Hulk Hogan - Albert Einstein - Tom Selleck
上面所说的集合可以是Arrays,ranges, sets, NSArray, NSSet等
其他值既不是falsey, 也不是collection,那么这个块就会被渲染一次:
datas: [ "user": [ "name": "Mario" "score": 1500 ] ] ------------- template: {{# user }} - {{ name }} - {{ score }} {{/ user }} -------------- rendering: - Mario - 1500
-
{{^items}}...{{/items}}
对应于上方的对立面data: [ "persons": [] ] -------------- template: {{# persons }} - {{name}} is {{#alive}}alive{{/alive}}{{^alive}}dead{{/alive}}. {{/ persons }} {{^ persons }} Nobody {{/ persons }} ------------- rendering: Nobody -------------- data: [ "persons": [ ["name": "Errol Flynn", "alive": false], ["name": "Sacha Baron Cohen", "alive": true] ] ] --------------- rendering: - Errol Flynn is dead. - Sacha Baron Cohen is alive.
-
-
Partial Tags
-
{{>partial}}
, 嵌入其他模块douc.mustanche Guests: {{# guests }} {{> person }} {{/ guests }} -------------- person.mustache {{ name }} ------------- data: [ "guests": [ ["name": "Frank Zappa"], ["name": "Lionel Richie"] ] ] -------------- rendering: Guests: - Frank Zappa - Lionel Richie
-
-
Partial Override Tags
-
{{<layout}}...{{/layout}}
, 模板继承layout.mustache // title , 和content 可以被覆盖 <html> <head> <title>{{$ title }}Default title{{/ title }}</title> </head> <body> <h1>{{$ title }}Default title{{/ title }}</h1> {{$ content }} Default content {{/ content }}} </body> </html> --------------- article.mustuche: {{< layout }} {{$ title }}{{ article.title }}{{/ title }} {{$ content }} {{{ article.html_body }}} <p>by {{ article.author }}</p> {{/ content }} {{/ layout }} --------------- data: [ "article": [ "title": "The 10 most amazing handlebars", "html_body": "<p>...</p>", "author": "John Doe" ] ] ---------------- rendering: <html> <head> <title>The 10 most amazing handlebars</title> </head> <body> <h1>The 10 most amazing handlebars</h1> <p>...</p> <p>by John Doe</p> </body> </html>
{{$ title }}...{{/ title }}
每次都会被渲染,并且只被渲染一次, no boolean checks, no collection iteration.一个模板可以包含很多partial override tags
避免循环
-
-
Set Delimiters Tags
{{=<% %>=}}
, 让你改变标签分隔符。
-
Comment Tags
{{! Wow. Such comment. }}
, 注释
-
paragma Tags
{{% CONTENT_TYPE:TEXT }} {{% CONTENT_TYPE:HTML }}