if ...!nunjucks中的真实条件渲染

nak*_*nak 7 templates nunjucks

if...true条件工作就像文档中概述的魅力一样.

但如果我尝试做类似的事情:

{% if !posts.length %}
<i>No project posts yet!</i>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

Template render error: (/home/nak/clones/mf3/views/project.html) [Line 10, Column 9]
 unexpected token: !
Run Code Online (Sandbox Code Playgroud)

我通过以下方式解决了这个问题:

{% if posts.length %}
{% else %}
<i>No project posts yet!</i>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

有没有更好(正确)的方法来做到这一点?

小智 21

我看到你在这里有一点点破旧的眩目.

尝试使用"not"而不是!

换句话说,不要使用,不要!!

给一个伙伴,并注意在这里的原始部分,他们突出显示不是一个关键词.

https://mozilla.github.io/nunjucks/templating.html#raw

祝你好运.


小智 5

您可以使用以下语法:

<% '' if posts.length else 'No project posts yet!' %>
Run Code Online (Sandbox Code Playgroud)

https://mozilla.github.io/nunjucks/templated.html#if-expression