Flask - Jinja Templates Example - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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.
Jinja supports different kinds of constructs for example conditional, looping, mathematical and etc. Let’s see some useful constructs.
Python 3.8.5
Flask 2.0.1
Mac OS X
(venv) flask-jinja-templates % 
.
├── app
│   ├── __init__.py
│   ├── routes.py
│   └── templates
│       └── index.html
└── jinja-templates.py
<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
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:
Now let’s pass the user object and see the output.
from app import app
from flask import render_template

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

Output:
Continuing with conditional constructs now we are going to look at loops in jinja language.
The loops are a very useful feature that allows us to work with a list of elements.
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.
<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:
Inside the code blocks, we are always allowed to assign variables using a set like below.
{% set country = 'India' %}
<p>I am from - {{country}}</p>
In jinja variables can be modified by filters, for example changing the cases and finding the length of any collection.
{% set hobbies = user.hobbies %}

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

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

Output:
So we have a lot of support from jinja to prepare the templates you can go through the jinja official documentation for more details.
Jinja templates
Flask HTML Templates
Happy Learning 🙂

Flask Simple HTML Templates Example
Hello World Flask Example
Python – How to install the Flask framework?
Rendering Static HTML page using Django
AngularJs Directive Example Tutorials
Angularjs Services Example Tutorials
Angularjs Custom Filter Example
How to push docker image to docker hub ?
Python Django Helloworld Example
How to access for loop index in Python
C How to Pass Arrays to Functions
Using Array in AngularJs Example
Python – AWS SAM Lambda Example
Step by Step Tutorials AngularJs Example
Python Tuple Data Structure in Depth

Flask Simple HTML Templates Example
Hello World Flask Example
Python – How to install the Flask framework?
Rendering Static HTML page using Django
AngularJs Directive Example Tutorials
Angularjs Services Example Tutorials
Angularjs Custom Filter Example
How to push docker image to docker hub ?
Python Django Helloworld Example
How to access for loop index in Python
C How to Pass Arrays to Functions
Using Array in AngularJs Example
Python – AWS SAM Lambda Example
Step by Step Tutorials AngularJs Example
Python Tuple Data Structure in Depth