How to Install and Use Python Jinja Template Engine

Jinja is a python module purely written in python. It is a template engine used by Python web frameworks like Django, Flask, etc.  So if you want to learn web development using python then you have to learn jinja templating syntax.

In this tutorial, we will learn How to install and use jinja in your python program for rendering templates.

Dependencies for using jinja

To use jinja template engine you will need some modules

  • Jinja works with Python 2.7.x and Python >= 3.5.
  • To install Jinja using PIP, then pip should be installed on your machine
  • distribute and setuptools (optional: to use the PackageLoader module)
  • To use jinja you must have the MarkupSafe module installed on your machine.

If you are going to install jinja with pip then MarkupSafe will be installed automatically.

How to Install Jinja2

The latest version of Jinja is known as jinja2. To install Jinja2 with pip, run the following commands;

pip install jinja2

How to use Jinja2 to render templates

To use jinja first import the Template instance from jinja module. The Template instance provides the render method that renders the text-based variables with the jinja pre-defined syntax.

Simple Jinja Example:

from jinja2 import Template
msg = Template('Hello, {{ name }}!')
out = msg.render(name='Mehrab Mohul')

print(out)

Output:

Hello, Mehrab Mohul!

Render Template with HTML files

When you will be live in web development with Python frameworks like Django or Flask, you need to render HTML files for extracting backend data to frontend. For this task, you can extend the jinja template syntax easily in your HTML files. See this example below;

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% block content%}
    
    {% endblock %}
</body>
</html>

You can learn Jinja from the sketch. Check out the Jinja tutorials below.

Posted in