close

How to use conditional if statements in Jinja 2?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to use conditional if statements in Jinja 2 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to use conditional if statements in Jinja 2?

  1. How to use conditional if statements in Jinja 2?

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

  2. use conditional if statements in Jinja 2

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

Method 1

General conditional syntax is like this:

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

Method 2

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() %}
    {%if mess == "Your Dog's breed is rufus"%}
     <div class="alert alert-warning alert-dismissible fade show" role="alert">
      {{mess}} 
    {% else %}
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
      {{"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> 
    </div>
    {% endfor %}

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read