Python Jinja Tutorial Part-I

Creating templates using Python jinja template engine

Jinja is a template engine for creating templates in python. Jinja is purely written in python and very similar to Django and Python templates. Using Jinja you can create very flexible and powerful templates easily. in this tutorial, we will learn, how to create and render templates using Jinja.

Why Jinja?

The name jinja is taken from one of the Japanese temples. But it is a python module to write templates. Jinja can be used to develop dynamic website along with the Flask python web development framework, However, Jinja is free to use and licensed under BSD.

Installing Jinja

As we stated before, Jinja is a python module. So you can install jinja via python PIP or easy install. So if you installed Python and pip on your machine, then to install jinja latest version called jinja2 run the following command:

pip install jinja2

Note: Sometimes pip is configured as pip3. In this case, use pip3 install jinja2

How to use Jinja?

Let’s create a python file that uses the Jinja templating module

from jinja2 import Template
name = "Jhon Doe"
template = Template('Hello, Welcome {{ name }}')
greeting = template.render(name=name)
print(greeting)

 Output

Hello, Jhon Doe

Example Explained

In the example above, at the very first line, we have imported the Template class from the jinja2 module. This allows the Template class to create a Template instance for creating templates.

In the 3rd line, we have created a Template instance and used a Jinja syntax {{ }} to print a rendered template. It is the power of jinja. Jinja can change the template syntax as the variable is defined. And it works outside a python file called template inheritance that we will learn in the part-II.

In the 4th line, we have rendered the template with the defined string variable in line two. and we have put the rendered template in the greeting variable. Finally, we have printed out greeting.

Example (Multiple Variables)

from jinja2 import Template
name = "Jhon Doe"
age = 32
template = Template("I'm {{ name }} and I'm {{ age }} years old")
info = template.render(name=name, age=age)
print(info)

Output

I’m Jhon Doe and I’m 32 years old

Rendering Lists

You can also work with python built-in lists for rendering multiple arbitrary objects. Here is an example;

from jinja2 import Template
person = ['Jhon Doe', 32]
template = Template("I'm {{ name }} and I'm {{ age }} years old")
info = template.render(name=person[0], age=person[1])
print(info)

Output

I’m Jhon Doe and I’m 32 years old

Dictionaries also work

You can also work with dictionaries for rendering multiple data using a single Template instance. Refer to the example below;

from jinja2 import Template
car = {'brand': 'Lamborghini', 'color': 'red'}
tm = Template("Brand: {{ car.brand }}\nColor: {{ car.color }}")
carInfo = tm.render(car=car)
print(carInfo)

Output

Brand: Lamborghini
Color: red

Jinja Scaping Data

You can escape HTML or XML entities using Jinja the escape class or the escape filter. Here how can we do this;

from jinja2 import Template, escape
html = 'h1This is a heading/h1'
tm = Template('{{ data }}')
tm1 = Template('{{ data | e}}')
output = tm.render(data=html)
output1 = tm1.render(data=html)

print(output) # without ecaping filter
print(output1) # using escaping filter
print(escape(html)) # using escaping function

Output

<h1>This is a heading</h1>
&lt;h1&gt;This is a heading&lt;/h1&gt;
&lt;h1&gt;This is a heading&lt;/h1&gt;

Example Explained

In the above code, we printed the first output normally, that’s why the HTML entities are not escaped. In the output1, we have used the Jinja filter system (Here | sign used to initialize the filter and e for escaping the string)

We can also use the escape function from Jinja module by imporing the escape class. The raw html has been scaped here using Jinja escape function in the output3.

Jinja Working with Object & Classes

See how can we use jinja in Python object and classes;

from jinja2 import Template

class Person:
    def __init__(self, name,age):
        self.name = name
        self.age = age
    def getAge(self):
        return self.age
    def getName(self):
        return self.name

person = Person('Jhon Doe', 34)

template = Template("I'm {{ per.getName() }} and I'm {{ per.getAge() }} years old")

msg = template.render(per=person)
print(msg)

Output

I’m Jhon Doe and I’m 34 years old

In the next tutorial, we will leaarn How to work with loop and conditionals in Jinja module. Check out the Part-II from the list below.

Posted in