Jinja2 Notes

What is it?

Jinja is a template engine (it is like a language on its own) that helps to place strings in documents. Essentially, you have a document with placeholders or variables called template. The data to be placed is provided by another file or from user.

Jinja takes the data from the user and places it at the placeholders in the template to give you the desired document.

This is more powerful than the built-in string formatter of Python.

It is used with Flask and Django web frameworks for making web pages.

However, it is generic in nature and can be used in many ways.

These notes are taken from a YouTube Tutorial on Jinja2 by Jason Rigden

Example

Let’s say that the template file had a sentence like this:

{{name}} had a little {{animal}}

Here, name is a variable and it is placed within backticks. Same with animal. The curly brackets are placeholders for the variables.

Suppose name = 'Mary' and animal = 'Lamb' are the values provided by the user.

Then Jinja will take these values and replace the variables in the template to give this file:

Mary had a little Lamb

Where is it used?

How to go about it?

How to start?

The following examples go from a simplistic case to an advanced case step-by-step.

Example 1: Read and Print a text file.

Note: This is a preliminary “Hello, World!” program to sort out the basics!

from jinja2 import Environment, FileSystemLoader
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
Hello, world!
template = env.get_template('hello_world.txt')
output = template.render()
print(output)
Hello, World!

This is the full code:

# Import the required methods
from jinja2 import Environment, FileSystemLoader

# Specify the template directory and environment 
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

# Create a template variable via environment
template = env.get_template('hello_world.txt')

# Render the template and create an output variable.
output = template.render()

# Print it out to see or export it to a new file as you see fit.
print(output)

Example 2: Adding Variables.

# Import the required methods
from jinja2 import Environment, FileSystemLoader

# Specify the template directory and environment 
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
{{name}} had a little {{animal}}.
# Create a template variable via environment
template = env.get_template('lamb.txt')

# Render the template and create an output variable.
output = template.render(name='Mary', animal='Lamb')

# Print it out to see or export it to a new file as you see fit.
print(output)
Mary had a little Lamb.

Example 3: Using Dictionaries

# Import the required methods
from jinja2 import Environment, FileSystemLoader

# Specify the template directory and environment 
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
{{data.name}} had a little {{data.animal}}.
# Create a template variable via environment
template = env.get_template('lamb.txt')

# Create a dictionary
person = {}
person['name'] = 'Mary'
person['animal'] = 'Lamb'

# Render the template and create an output variable.
output = template.render(data=person)

# Print it out to see or export it to a new file as you see fit.
print(output)
Mary had a little Lamb.

Example 4: Using if-else statements.

# Import the required methods
from jinja2 import Environment, FileSystemLoader

# Specify the template directory and environment 
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
{% if truth %}
    This is true
{% else %}
    This is false
{% endif %}
template = env.get_template('truth.txt')
output = template.render(truth=True)
print(output)
This is true
template = env.get_template('truth.txt')
output = template.render(truth=False)
print(output)
This is false

Example 5: For loops using lists/tuples

# Import the required methods
from jinja2 import Environment, FileSystemLoader

# Specify the template directory and environment 
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
{% for colour in colours %}
    {{colour}}
{% endfor %}
template = env.get_template('rainbow.txt')

colours = ['red', 'green', 'blue']
output = template.render(colours=colours)
print(output)
red

green

blue

Example 6: Template inheritance - combine blocks from multiple places.

# Import the required methods
from jinja2 import Environment, FileSystemLoader

# Specify the template directory and environment 
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
<head>
    <title>{{title}}</title>
</head>
<html>
    {% include 'header.html' %}
    <body>
    </body>
</html>
template = env.get_template('base.html')

output = template.render(title="Hey, there!")
print(output)
<html>
    <head>
        <title>Hey, there!</title>
    </head>
    <body>
    </body>
</html>

Observation: Here, the base.html file automatically called header.html file. And inside it, the title variable was automatically placed.

Example 7: Template rendering + Placing data in body tag

# Import the required methods
from jinja2 import Environment, FileSystemLoader

# Specify the template directory and environment 
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
<head>
    <title>{{title}}</title>
</head>
<html>
    {% include 'header.html' %}
    <body>
    {% block content %}
    {% endblock %}
    </body>
</html>
{% extends "base.html" %}

{% block content %}

    <p>
        {{body}}
    </p>

{% endblock %}
template = env.get_template('child.html')

output = template.render(title="Hey, there!", body="Brown cow!")
print(output)
<html>
    <head>
        <title>Hey, there!</title>
    </head>
    <body>
        <p>
            Brown cow!
        </p>
    </body>
</html>