Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if variable and variable is defined - jinja2

Tags:

jinja2

I'm trying to show divs dependent on whether a database entry has been made:

<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>

This is a simplified snippet - the pattern carries on. Basically if the title is in the database show only div1 if both title 1 and title 2 are in the database show div1 and div2 and so on.

Currently this sort of works as it shows the div I want to show but for some reason it shows the next one as well. If I have title for div 1 it shows 1 and 2, if I have a title for div 1 and 2 it shows 1, 2, and 3

I am really confused as I am really new to Jinja2. I am not sure if it's my positioning of the syntax in the html, or if the syntax is wrong, or if you are not able to check across two variables ... any help would be appreciated.

like image 997
Jesse Avatar asked Sep 04 '12 23:09

Jesse


Video Answer


1 Answers

As in Python, the 0, None, [], {} and "" are False. Anything other than that, it's True.

"The if statement in Jinja is comparable with the if statements of Python. In the simplest form you can use it to test if a variable is defined, not empty or not false:"

{% if post and post.wrk_1_title %}

{% endif %}

Documentation: http://jinja.pocoo.org/docs/templates/#if

like image 62
Shankar Cabus Avatar answered Oct 14 '22 20:10

Shankar Cabus