Intermediate

Jinja2 is a templating engine designed for Python which can also be used with the famous Python web frameworks i.e Django and Flask. Jinja is inspired by the Django Templating Language (DTL) and it can be used to create documents, a large number of emails, and develop dynamic programs and HTML pages.

At the beginning of the internet era, there was no templating language. The HTML files used to consist only of static data, which was sent to the client when requested, which means that the same data was sent to every client irrespective of their region and language, etc. But now things have changed, thanks to the templating engines like jinja we can send the HTML files to the client-side after rendering it according to the client’s request. Templates are used for rendering dynamic content which can contain variables or expressions.

In this article, we are going to see how we can use python in web development. Web applications are now easier to create using python due to its low learning curve. We will learn how to create dynamic HTML files using python’s famous package Jinja2.

Installation

To install Jinja2 on our server we will use the pip3 command in our prompt. I will be using “WindowsPowershell” to install Jinja2.

 pip3 install jinja2  

Note: Command may vary according to tool or OS used.

Hello World in Jinja2

As one of the programming essentials let’s start by printing hello world on the console using Jinja2. The first module we shall look at is “Template” of Jinja2. We shall “render” the text on the console for now.

#jinja.py
from jinja2 import Template #import Template module

template = Template("Hello World!")
print(template.render())

Output

Hello World Output

In the code above we have created an instance of Template passing “Hello World” string as a parameter which in return gives us a method render. The render method allows us to access the templated string.

Creating a Web Server

To render HTML forms we need to spin a web server. In Python, we have two popular frameworks for this purpose Flask and Django. Django is a very vast framework while flask is a micro framework that is secure and easy to use.

If you are not sure how to create a flask application please refer to the following link: https://flask.palletsprojects.com/en/1.1.x/installation/

How to define Variables

Data is passed to the template as a parameter which is then replaced by the variable name on runtime by jinja, for this purpose jinja has some predefined delimiters. To perform simple functionalities like displaying the parameters and assigning the value to a variable we use the following jinja format:

{{ variable_name }}

First, we’ll see how we can print variables using the Jinja2 template in our console. To demonstrate we shall be using the template module. As you can see we have assigned a string to the “template” variable. The “{{ }}” tells the template that anything inside this symbol should not be treated as a string rather it is a variable and should be replaced by the data at runtime. We can also pass the data using a dictionary in python. The Render method allows us to pass the parameter to the template object.

#jinja.py
from jinja2 import Template

template = """Animal {{ animal }}
Color {{ color }}
Tree {{ tree }}
Language {{ language }}
"""

data = {
	"animal": "Cat",
	"color": "Red",
	"tree": "Apple",
	"language": "English",
}

jinja_template = Template(template)

print(jinja_template.render(data))

Output:

Now let’s create an HTML page using Flask as a backend server. Flask by default searches for the HTML files inside the “templates” and It is a good practice to put your HTML files inside it.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{{ data.title }}</title>
</head>
<body>
    <h1> Hello World! </h1>
    <h2> I love {{ data.language }} language!</h2>

</body>
</html>

Using flask we will create a python file to render the HTML file. The render_template function that comes with flask helps in rendering the HTML file. It requires two parameters, the HTML filename, and the data which will be displayed instead of the placeholders inside the HTML file.

# app.py
from flask import Flask,render_template      	 


data = {
    	"title": "Jinja2!",
    	"language": "Python",
    	}

app = Flask(__name__, template_folder='templates')     	 



@app.route("/")              	 
def hello(data=data):                 	 
	return render_template('index.html',data=data)    	 

if __name__ == "__main__":   	 
	app.run()   	

Output:

As we can see in the output image “{{  }}” delimiter was replaced by the data inside the variable. We have successfully executed our first Jinja2 code.

Conditional Statements

We have seen how to pass parameters to an HTML page and how to display those parameters as required using Jinja2. Now another advantage of using Jinja2 is that we can create logical and iterative statements inside the HTML page.

We shall see how to write Single and multi-line conditional statements and for loops in Jinja2. All conditional statements are executed in the predefined delimiter that is:

{% .. %}

If Statements

The format for writing a single if statement in Jinja2 is:

{% if something %}
 	...
    {% endif %}

Please note we need to remember to close the if statement unlike in Python syntax as it needs to know when it has reached the end of the block. Let’s try a real-time example to see.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>If Statements</title>
</head>
<body>
    <h1>If statement in Jinja!</h1>
   	 {% if value %}
   	 <h2>I'm in If</h2>
   	 {% endif %}
</body>
</html>
#app.py
from flask import Flask,render_template      	 

value = True
app = Flask(__name__, template_folder='templates')     	 


@app.route("/")              	 
def ifStatement(value=value):                 	 
	return render_template('index.html',value=value)    	 

if __name__ == "__main__":   	 
	app.run()

Output

As you can see in the output, the if statement got executed as the h2 tag was displayed.

For IF-ELSE the syntax given below is used. We need to write the python code in “{% %}” delimiter. We will try a real time example while understanding “for loops” in Jinja further on.

{% if something %}
{% elif something %}
{% else %}
 ...
{% endif %}

FOR Loop

Jinja2 only supports for loop and the syntax followed is:

{% for item in list %}
    ....
{% endfor %}

Similar to if statements ending the for loop is a must. “endfor” tag is a must or otherwise the HTML file will not know when the for loop execution has ended. In the example below we will demonstrate how to find out whether a value is even or odd in the list using jinja2 in an HTML page.

#app.py
from flask import Flask,render_template      	 

my_list = [2,3,7,4]
app = Flask(__name__, template_folder='templates')     	 


@app.route("/")              	 
def ifForStatement():                 	 
	return render_template('index.html',my_list=my_list)    	 

if __name__ == "__main__":
	app.run()  	
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>For Loop</title>
</head>
<body>
    <h1>For Loop in Jinja!</h1>
   	 {% for data in my_list %}
   	  <li> {{ data }}</li>
   	 {% if (data % 2)==0 %}
   	 <h5>I'm an even number</h5>
   	 {% else %}
   	 <h5>I'm an odd number</h5>
   	 {% endif %}
   	 {% endfor %}
</body>
</html>

Output:

Inheritance

Template Inheritance is one of the main reasons why web developers use jinja templating engines. In web development  it is widely observed that the codes for the components like header,footer and navigation bar are repeated in every HTML page. Since the basic rule of development is to keep your code “DRY” i.e don’t repeat yourself, the jinja template inheritance helps us to follow this convention. The base template of other pages known as parent template can be extended into the child template using the following jinja2 format.

In Parent template the format that is followed is:

{% block %}
    ----
{% endblock %}

In the child template the format that is followed is:

{% extends "Parent Template FileName" %}

The block tag in the parent template (index.html) represents that child template tags can override it. In the child template (child.html) the extends tag should always be on the top. It first renders the parent template than overrides data in other block tags.

# app.py
from flask import Flask,render_template      	 

my_list = [2,3,7,4]
app = Flask(__name__, template_folder='templates')     	 


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

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

if __name__ == "__main__":
	app.run()      
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
	{% block head %}
	<title>{% block title %}{% endblock %} - Base Template</title>
	{% endblock %}
</head>
<body>
	<div id="content">{% block content %}
   				   {% endblock %}
    </div>
	<div id="footer">
    	{% block footer %}
    	<h4 style="background-color: red; text-align: center;">This is My Footer</h4>
    	{% endblock %}
	</div>
</body>
</html>
<!-- child.html -->
{% extends "index.html" %}
{% block title %}Child Template{% endblock %}
{% block head %}
	{{ super() }}
{% endblock %}
{% block content %}
	<h1>Child Template</h1>
	<p>
  	This is my Child Template!
	</p>
{% endblock %}

Output:

Commenting In Jinja2

Commenting your code is one of the most important duties of a professional programmer. Commenting the code helps you and other fellow programmers to better understand the code later in the project. To add comments in your code following jinja syntax is used:

{# .Add your comments here. #}
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
	<title>Comments</title>
</head>
<body>
    <h1>Commenting</h1>
    {# note: commented-out
	<h1>If statement in Jinja!</h1>
    	{% if value %}
    	<h2>I'm in If</h2>
    	{% endif %}
    	#}
</body>
</html>

Include

We learned about extends, now let’s look at how to include an HTML file. The include tag is extremely useful as it returns the files content into the current file. To include the following syntax is used :

{% include 'filename.html' %}

What if the file didn’t exist it is good practice to use “ignore missing” so HTML page when rendered won’t give an error.

{% include "navbar.html" ignore missing %}

Line Statements

In Jinja2 if the application allows line statements then mark a line as a statement. This is possible if there is no text between the line statements. The format for writing line statement is:

#...##

We saw a for loop example above now let’s write a line statement equivalent to the for loop.

<ul>
# for data in my_list
    <li>{{ item }}</li>
# endfor
</ul>

You can also add a colon (:) in the for loop for better readability. For loop will return the same output as the above example.

Subscribe to our newsletter

Error SendFox Connection: 403 Forbidden

403 Forbidden