[Django]-How to use conditional if statements in Jinja 2?

47👍

General conditional syntax is like this:

{% if some_variable == some_value %}
    {{ do_something }}
{% endif %}

Docs have some more examples.

👤xyres

4👍

Note: mess is a variable

Below code syntax for using ‘for loop’ and ‘if statements’ in Python Language together with Jinja in HTML file:

{% for mess in get_flashed_messages() %}
    {% if mess == "Your Dog's breed is rufus" %}
        {{mess}} 
    {% else %}
        {{"Don't you have any other breed?"}}
    {% endif %}      
{% endfor %}

And below is the code if your using Jinja with Bootstrap in HTML file:

{% for mess in get_flashed_messages() %}
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
        {% if mess == "Your Dog's breed is rufus" %}
            {{mess}} 
        {% else %}
            {{"Don't you have any other breed?"}}
        {% endif %}      
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
{% endfor %}

Leave a comment