Flask Website –Creating Jinja Template Python

To create an impressive website uniformity and consistency is essential among its web pages. This uniformity is in terms of color scheme, typography and placement of the elements. It also involves creation of menus and links, blocks and buttons, animation and formatting.  To create consistent looking web sites or applications, you can use templates. Jinja Template Python is the template system that helps in creating standard templates across website. These templates are used to give homogeneous look and feel to individual pages of a website.

A Jinja Template Python is created by defining different block elements to make a skeleton template. This skeleton template is the main template inherited by web pages and is also called the base template. The attributes in the base template are inherited by the pages which extend the base template. The inheriting pages are called the child pages. The inheriting page replaces the attribute elements of the template page with its page-specific content before rendering.

To create templates in Python Flask, Jinja2 allows the combination of variables and programming logic.

How to Create a Jinja Template Python?

Jinja allows you to add the programming logic or block elements within {%   %} and the template is saved as an .HTML or .HTM file.

You can use conditional logic like if-else statement or repetitive logic using loops (for, while) within the {%   %} parenthesis. A variable name passed on from other sections of a web application can be used in HTML document enclosed in {{}}.

To create template the components or sections of web pages are identified. Each of this section or component in template is defined as a block. Blocks are created in this way

{% block name-of-block %}

{% end block %}

In the child template or the web page the content is to be displayed must be enclosed in the same Jinja2 block components.

For example if you want to add text in body section of different pages, you need to add relevant block in the template like this.

{% block body %}
{% end block %}

In the child web page the text or content to be rendered will be specified in the above mentioned attributes.

How the template is used?

After creating the template it is saved as an HTML file. For the sake of simplicity such a template is very commonly named as layout.html. This layout file must be extended in the child page. It is extended by adding extends statement at the top of each web page that have to be rendered with the defined template.

{% extends
"name of html layout file" %}
{% extends "layout.html" %}

Example

The example that we have shown here is created using bootstrap CSS style. Menu is created in the layout.html. In the layout the following Jinja2 template elements are created

{% block title %}{% endblock %}- for title of the web page

{% block pagetitle %}{% endblock %}- for defining the top text for the webpage content

{% block content %}{% endblock %}- for defining the main content of the page

application.py – contains all the routes of this website

from flask import Flask, render_template

app=Flask(__name__)

@app.route('/')
def index():
    return "Welcome to your Python Flask Website!!"
    
@app.route('/welcome')
def welcome():
    return render_template('welcome.html')  

@app.route('/next')
def next():
    return render_template('next.html')

layout.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
	<div class="container">
	<div class="navbar navbar-light" style="background-color: #e3f2fd;">
	<a href="#">Home</a>
	<a href="buyer.html">Buyer</a>
	<a href="seller.html">Seller</a>
	<a href="product.html">Products</a>
	</div>
	<div class="row">
	<div class="column side">
	<h2>{% block pagetitle %}{% endblock %}</h2>
	</div>
	</div>
	<div class="row">
	<div class="column side"> </div>
	<div class="column middle">
    <div id="content .mr-3 ">{% block content %}{% endblock %}</div>
	</div>
	</div>
	<div id="footer">
        Copyright 2008 by us
    </div>
	</div>
</body>
</html>

In welcome.html and next.html pages the content included in these template elements in the child html page will be rendered in the browser.

welcome.html

{% extends "layout.html" %}
<HTML>
<head>
<title>
{% block title %}
My template website
{% endblock %}
</title>
</head>
<BODY>
{% block pagetitle %}
This is the heading of page content
{% endblock %}
{% block content%}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis dignissim orci sed purus ultrices, nec suscipit ex lacinia. Proin at luctus mauris. Proin lacinia erat pellentesque odio vestibulum aliquam. Nulla facilisi. Aliquam venenatis metus purus, a rhoncus eros tristique at. In sit amet nibh tristique, pulvinar nulla dignissim, consequat ipsum. Mauris congue, magna ac dignissim pulvinar, nibh ex mattis libero, nec pharetra lacus nibh rutrum felis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam tortor lorem, efficitur vitae risus vestibulum, posuere pharetra erat. Curabitur mollis mauris ut odio tempus iaculis.
</p>
<p>Vestibulum bibendum molestie dignissim. Donec nunc risus, convallis sed dignissim in, interdum eu diam. Nunc ullamcorper est ac sem eleifend scelerisque. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus nec urna nulla. Maecenas erat ex, rhoncus ut sollicitudin sit amet, iaculis tincidunt libero. Nunc laoreet magna lacus, quis aliquet ex ultrices quis. Phasellus quis neque a lorem consequat consequat. Cras rhoncus, orci ut dapibus ornare, sem est tempor dui, et egestas dolor est ut leo. Sed placerat egestas ante, a commodo libero volutpat vel. Cras lobortis lorem et tortor ullamcorper facilisis.
</p>
<p>Donec at pharetra nibh. Praesent tristique aliquet interdum. Fusce eget vehicula mi. Donec egestas magna et odio consequat, non fringilla enim auctor. Phasellus at est non nisl suscipit molestie. Quisque ac dignissim magna. Vestibulum arcu tellus, auctor et risus non, vulputate placerat turpis. Phasellus eu velit purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pellentesque porttitor auctor. Suspendisse faucibus, nulla vitae fringilla venenatis, sapien nulla mollis mi, sed scelerisque dolor turpis vitae tellus. Duis viverra gravida faucibus. Maecenas varius diam eu diam dictum, nec sodales diam fringilla. Praesent vel est at ipsum dictum semper.
</p>
<p>Nunc lectus lorem, tincidunt a rhoncus sit amet, luctus vel massa. Nam interdum id est ac pharetra. Duis euismod facilisis pretium. Phasellus venenatis dolor vitae posuere placerat. Morbi odio elit, sollicitudin ut arcu et, euismod tincidunt odio. Donec varius turpis elit, a fermentum purus maximus quis. Nullam euismod risus et mollis iaculis. Sed at elit pharetra, interdum enim in, interdum leo. Aenean arcu erat, elementum gravida augue vel, suscipit vehicula dui. Sed iaculis dolor id magna ultricies mattis. Ut fringilla vehicula purus at dapibus. Phasellus rutrum magna velit, sed convallis dui consequat at.
<a href={{url_for('next')}}>NEXT</a></p>

{% endblock %}
</BODY>
</HTML>
Jinja Template Python Example

next.html

{% extends "layout.html" %}
<HTML>
<BODY>
{% block pagetitle %}
<h1> This is the Next page of my site!!to go back to welcome page click back link </h1>
<a href={{url_for('welcome')}}>BACK</a>
{% endblock %}
</BODY>
</HTML>

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *