如果变量存在且已定义 - jinja2

13

我正在尝试根据数据库条目的存在性来显示div

<table class="info-table">
<tr><td>
<div class="info-table_titlebox">
{% if post.wrk_1_title is defined %}
    <div class="info-title_title">
    <h2>{{post.wrk_1_title}}</h2>
    <h3>Facilitator: {{post.wrk_1_facilitator}}</h3>
    <h4>Location: {{post.wrk_1_locate}}</h4>
    <h4>Max participants: {{post.wrk_1_max}}</h4>
    </div>
    <div class="info-title_list">
        <ul>
        <li>{{post.eventday}} - <b>Week {{post.eventweek}}</b></li>
        <li class="info-title_listright">{{post.wrk_1_time}}</li>
        </ul>
    </div>
    <p>{{post.wrk_1_description}}</p>
{% endif %}
</div>
</td>
<td>
<div class="info-table_titlebox">
{% if post.wrk_1_title is defined and post.wrk_2_title is defined %} 
    <div class="info-title_title">
    <h2>{{post.wrk_2_title}}</h2>
    <h3>Facilitator: {{post.wrk_2_facilitator}}</h3>
    <h4>Location: {{post.wrk_2_locate}}</h4>
    <h4>Max participants: {{post.wrk_2_max}}</h4>
    </div>
    <div class="info-title_list">
        <ul>
        <li>{{post.eventday}} - <b>Week {{post.eventweek}}</b></li>
        <li class="info-title_listright">{{post.wrk_2_time}}</li>
        </ul>
    </div>
    <p>{{post.wrk_2_description}}</p>
{% endif %}
</div>
</td>

这是一个简化版的代码片段 - 模式继续。基本上,如果标题在数据库中,则只显示div1,如果title1title2都在数据库中,则显示div1div2等等。

目前这种方式有点奇怪,因为它显示了我想要显示的div,但同时也显示了下一个div。如果我为div1的标题设置了标题,它会显示12,如果我为div12的标题设置了标题,它会显示1, 2和3

我真的很困惑,因为我对Jinja2非常陌生。我不确定是我在HTML中的语法定位错了,还是语法错误,或者你不能检查两个变量……任何帮助都将不胜感激。


你确定jinja变量在上下文中没有被定义吗?您可以通过将{% if post.wrk_1_title is defined and post.wrk_2_title is defined %}拆分为两个if,并查看生成的HTML来测试这一点。 - voscausa
@vocausa 我有点不确定 "defined" 是什么意思,我假设当一个条目被添加到数据库中但是没有从表单提交中添加任何内容时,这意味着当从数据库中检索此条目时,它起初是 "undefined"。一开始我以为它会显示为 "None",但似乎它确实会创建一个条目...也许是一个空字符串?因此,通过检查是否 "defined",如果存在一个条目,它将显示此 div。 - Jesse
定义了一个值为 None 的变量。未定义的意思是:该变量不为已知。 - voscausa
是的,我终于弄清楚了。我最终创建了一个过程,如果将空字符串添加到数据库中,则输入“None”,然后使用{% if post.wrk_1_title is not none %}来显示div,如果恢复了适当的变量。 - Jesse
1个回答

39

在Jinja中,与Python中的if语句相似。在最简单的形式中,您可以使用它来测试变量是否已定义、非空或非假:

和Python一样,0, None, [], {}""是False。除此之外的任何值都为True。

{% if post and post.wrk_1_title %}

{% endif %}

文档: http://jinja.pocoo.org/docs/templates/#if

该文档介绍了Jinja模板引擎中的条件语句(if)用法。请参考以上链接。

只是为了确认我理解上述声明,您的意思是jinja定义是用于检查是否存在变量的测试吗? - Jesse
是的,但是“post”应该被定义。如果您不知道“post”是否被定义,您应该测试它:“post and post.wrk_1_title”。 - Shankar Cabus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接