检查Jinja2中的数组是否不为空 [英] Check if an array is not empty in Jinja2
本文介绍了检查Jinja2中的数组是否不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检查在index.html
中是否定义了变量texts
.
I need to check if the variable texts
is defined or not in index.html
.
如果定义了变量并且不为空,那么我应该渲染循环.否则,我想显示错误消息{{error}}
.
If the variable is defined and not empty then I should render the loop. Otherwise, I want to show the error message {{error}}
.
基本上在PHP中
if (isset($texts) && !empty($texts)) {
for () { ... }
}
else {
print $error;
}
index.html
{% for text in texts %}
<div>{{error}}</div>
<div class="post">
<div class="post-title">{{text.subject}}</div>
<pre class="post-content">{{text.content}}</pre>
</div>
{% endfor %}
我在Jinja2中怎么说?
How do I say this in jinja2?
推荐答案
Take a look at the documentation of Jinja2 defined()
: http://jinja.pocoo.org/docs/templates/#defined
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
是否足够清楚?在您的情况下,它可能看起来像这样:
Is it clear enough? In your case it could look like this:
{% if texts is defined %}
{% for text in texts %}
<div>{{ error }}</div>
<div class="post">
<div class="post-title">{{ text.subject }}</div>
<pre class="post-content">{{ text.content }}</pre>
</div>
{% endfor %}
{% else %}
Error!
{% endif %}
这篇关于检查Jinja2中的数组是否不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文