Uncategorized

How To Use Jinja Template Engine

Introduction of Jinja

Jinja is a Python template engine. It allows us to easily define dynamic blocks of HTML which are populated by Python. HTML templates are useful even for static websites which have multiple pages. Usually, there are some common elements, such as headers and footers, on every page. Although it is possible to maintain each page individually for static websites, this requires that a single change be made in multiple places if the change is made to a shared section.

Flask was built on top of Jinja, so although it is possible to use Jinja without Flask, Jinja is still an inherent part of Flask, and Flask provides several methods to work directly with Jinja. Generally, Flask assumes nothing about the structure of your application except what you tell it, and prefers providing functionality through optional plugins. Jinja is somewhat of an exception to this. Flask gives you Jinja by default, and assumes that you store all your Jinja templates in a subdirectory of your application named templates.

Basic use of Jinja templates

The first step to using Jinja templates is creating a directory in our application to contain our template files, so navigate to your headlines directory, and create a directory called templates. Unlike the previous steps, this name is expected by other parts of the application and is case sensitive, so take care while creating it. At the most basic level, a Jinja template can just be an HTML file, and we’ll use the .html extension for all our Jinja templates.

Create a new file in the templates directory called home.html. This will be the page that our users see when visiting our application, and will contain all the HTML that we previously had in a Python string.

Step 1

This is the normal code written in python for HTML, Now we use the jinja to write a HTML .

code

Step 2

Make a separate file of the HTML in the templates folder with .html extension with same directory

html

Step 3

make some changes import render_template, on the last write return render_template(“your html file name.html”)

change code

Step 4

You get the output like above if you want to learn more click here

Share This Post To Your Friends

Similar Posts

Leave a Reply

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