简洁
nunjucks
(下称nj
)是mozilla
推出的一款模板语言,因语法与我们熟悉的JS、C#等语法差异较大,使用成本较高。说实话,个人觉得这语法挺反人类的,不知道egg为啥要选它作为默认模板语言……
官网:https://mozilla.github.io/nunjucks/cn/getting-started.html
常见用法
- 基本语法:
{{表达式}}
; - 注释:
{# 这是注释 #}
需要注意的是语法和vue冲突了,如果想在layout中直出Vue的template代码需要另外想办法。
三元运算符
- js:
success ? 'true' : 'false'
; - nj:
{{ "true" if success else "false" }}
;
默认值
- js:
success || 'default'
; - nj:
{{ success if success else "default" }}
;
可选链
- js:
data?.success
; - nj:
{{ (data if data else {}).success }}
; - 也可以:
{{(data or {}).success}}
if-else代码块
- js:
if (success) {
// xxx
} else if (checked) {
// xxx
} else {
// xxx
}
- nj:
{% if success %}
xxx
{% elif checked %}
xxx
{% else %}
xxx
{% endif %}
与或非
js:
if (a && b) {
}
if (i == 0 && !a) {
}
if ((x < 5 || y < 5) && b) {
}
nj:
{% if a and b %}...{% endif %}
{% if i == 0 and not a %}...{% endif %}
{% if (x < 5 or y < 5) and b %}...{% endif %}