Flask templates can do much more than replacing the placeholders that we have done in the previous tutorial, In this tutorial, we are going to see the most powerful features of the Flask template engine.

Flask Jinja Templates:

The template engine used by Flask is a very powerful package that jinja that’s being installed as part of the Flask installation.

A Jinja template can contain variables or expressions ideally these are placeholders expressed with {{}} which will get replaced with the actual dynamic values when it renders the page on the browser.

Flask Jinja Templates Example:

Jinja supports different kinds of constructs for example conditional, looping, mathematical and etc. Let’s see some useful constructs.

Versions:

  • Python 3.8.5
  • Flask 2.0.1
  • Mac OS X

Application Structure:

(venv) flask-jinja-templates % 
.
├── app
│   ├── __init__.py
│   ├── routes.py
│   └── templates
│       └── index.html
└── jinja-templates.py

Creating simple if-else construct:

app/templates/index.html
<html>
    <head>
        <title>Hello, World!</title>
    </head>
    <body>
        <h1 style="color:#093657"> Hello,
            {% if user %}
                {{user.name}}
            {% else %}
                Buddy!
            {% endif %}
        </h1>
    </body>
</html>

On the above code, I created a conditional User name that will provide an alternative user name Buddy when user not provided in the render template call.

If you observe these conditional constructs are very similar to how we work with if statements in python.

create routes.py

app/routes.py
from app import app
from flask import render_template

@app.route('/')
def index():
    user = {
        'name':'Chandra'
    }
    return render_template('index.html')

In the routes.py above, I am not passing the user object to render_template() function to see alternative user name in the browser.

Output:

Flask Jinja Templates Example

Now let’s pass the user object and see the output.

app/routes.py
from app import app
from flask import render_template

@app.route('/')
def index():
    user = {
        'name':'Chandra'
    }
    return render_template('index.html', user=user)

Output:

Flask Jinja Templates Example 2

Continuing with conditional constructs now we are going to look at loops in jinja language.

Creating for construct:

The loops are a very useful feature that allows us to work with a list of elements.

routes.py

app/routes.py
from app import app
from flask import render_template

@app.route('/')
def index():
    user_info = {
        'name':'Chandra',
        'hobbies':['Blogging','Reading Books','Playing chess'],
        'interested_books':{
            'Java':['Thinking in Java','Inside the Java virtual machine'],
            'Python':['Fluent Python']
        }
    }
    return render_template('index.html', user=user_info)

on the above, I have created a little complicated user data that containing strings, a list of strings and a dict inside another dict.  Let’s see how we can use jinja is being used to populate this data.

app/templates/index.html
<html>
    <head>
        <title>Hello, World!</title>
    </head>
    <body>
        <h1 style="color:#093657"> Hello,
            {% if user %}
                {{user.name}}
            {% else %}
                Buddy!
            {% endif %}
        </h1>
        Hobbies:
        <div>
            <p><ul>
                {% for hobby in user.hobbies %}
                <li>{{hobby}}</li>
                {% endfor %}
           </ul></p>
        </div>
        Interested Books:
        <div>
            <p><ul>
                {% for key in user.interested_books %}
                    {{key}}
                    <ul>
                    {% for book in user.interested_books.get(key)%}
                        <li>{{book}}</li>
                    {% endfor %}
                    </ul>
                {% endfor %}
           </ul></p>
        </div>
    </body>
</html>

The jinja for loops are very similar to how we use the for loops in python, that difference is that all structures are enclosed in {% %} this is what the jinja used to detect these control structures.

The {{}} is used for placeholder variables.

Output:

Flask Jinja Templates Example loops

Assignments:

Inside the code blocks, we are always allowed to assign variables using a set like below.

app/routes.py
{% set country = 'India' %}
<p>I am from - {{country}}</p>

Filters:

In jinja variables can be modified by filters, for example changing the cases and finding the length of any collection.

app/routes.py
{% set hobbies = user.hobbies %}

{{ 'Hobbies length: ' ~ hobbies | count }}</br>

{% set name = user.name | upper  %}
Name in upper - {{ name}}

Output:

Flask Jinja Templates Example filters

So we have a lot of support from jinja to prepare the templates you can go through the jinja official documentation for more details.

References:

Happy Learning 🙂