Using Jinja2 for Easy Templating

·

3 min read

This article will primarily focus on how to use Jinja2 for most of your templating needs over a few general scenarios like:

  • Similar mail text for multiple recipients
  • Re-usable HTML start-up (index.html) page
  • Rendering JSON results into a well formatted table

Before we jump in, a quick brief about Jinja.

Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document.

Install jinja using the below command, assuming that you already have python installed in your system.

pip install -U Jinja2

CASE 1: EMAIL

If you have an email that would like to send to multiple recipients which is personally addressed to them, you could take jinja's help to make the whole process much simpler for you.

  • Make a new project
  • Create templates directory within it
  • Place the contents of the mail to a file and replace the dynamic fields as {{ tags }} as show below:
/templates/email.txt

Dear {{user}},
It brings me great joy to share an amazing news with you,
you have been shortlisted for our {{program}}, and we would
like you to follow a few instructions for us:
1. You need to report at office on {{date}} at {{time}}
2. Bring your personal laptop along
3. Pre-Paperwork for onboarding formalities
Many thanks,
{{manager}}
{{team}}
  • Create a .py file with the starter code as shown below:
example.py

from jinja2 import Environment, FileSystemLoader

environment = Environment(loader=FileSystemLoader("templates/"))
template = environment.get_template("email.txt")

message = template.render(
    {
        "user": "Milo",
        "program": "Little Lamps Program",
        "date": "26-08-2022",
        "time": "10:00 AM",
        "manager": "Pakhi",
        "team": "Creative Division",
    }
)

print(message)

The printed message will have the replaced value with whatever values you had fed in for the template to render.

Dear Milo, It brings me great joy to share an amazing news with you, you have been shortlisted for our Little Lamps Program, and we would like you to follow a few instructions for us:

  1. You need to report at office on 26-08-2022 at 10:00 AM
  2. Bring your personal laptop along
  3. Pre-Paperwork for onboarding formalities Many thanks, Pakhi Creative Division

CASE 2: HTML PAGE

Similar to the case above, create your sample_index.html under templates folder.

sample_index.html

<html>
<head>
  <title>{{title}}</title>
</head>

<body>
  <h1>{{about}}</h1>
  <p>{{description}}</p>
</body>

</html>
from jinja2 import Environment, FileSystemLoader

environment = Environment(loader=FileSystemLoader("templates/"))
template = environment.get_template("sample_index.html")

message = template.render(
    {
        "title": "HASHNODE JINJA DEMO",
        "about": "Using Template Examples",
        "description": "In step wise approach of templating, with scenarios from day to day life",
    }
)

# w+ is to create a file if not present
with open("index.html",'w+') as f:
    f.write(message)

CASE 3: JSON RESULTS IN TABULAR FORMAT (with html tags)

Create a new file under template, ex: table (as in the below example)

table

<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 80%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: center;
  padding: 2px;
  width: fit-content;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>
<table>
    <tr>
        {% for key, value in data[0].items() %}
        <th>{{key}}</th>
        {% endfor %}
    </tr>
    {% for i in range(data|length) %}
    <tr>{% for key, value in data[i].items() %}
        <td>{{ value }} </td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

In the example.py provide your json_data as shown:

from jinja2 import Environment, FileSystemLoader

environment = Environment(loader=FileSystemLoader("templates/"))
template = environment.get_template("table")

json_data = {
    "data": [{"Id": 1, "Number": 45, "Name": "Milk"},
    {"Id": 2, "Number": 46, "Name": "Cheese"},
    {"Id": 3, "Number": 47, "Name": "Butter"},
    {"Id": 4, "Number": 48, "Name": "Cream"},
    {"Id": 5, "Number": 49, "Name": "Curd"},
    {"Id": 6, "Number": 50, "Name": "Yogurt"}

    ]
}

message = template.render(json_data)
# w+ is to create a file if not present
with open("index.html", "w+") as f:
    f.write(message)

Capture.JPG

Hope these examples were useful for you and will make it easier to handle templates and make them automatable.