From the last blog, we know 3 methods to write a string from our own templates.

In this blog, I would love to share some basic writing of the templates using Jinja 2.


Prerequisites

We need to have jinja 2 library installed.

Jinja — Jinja Documentation (3.1.x)

And we can begin.


1. Put into a string

Start from writing variables into a Jinja2 template.

Jinja2 template

  • {{<variable>}} to display a single variable.
  • {{<dict>.<field>}} to display a particular key of a dict.
  • {# <comment> #} to specify comments.
  • '{{ }}' to display quotes.

Python script

Using Jinja2.Template(template).render(data) to render a substituted string.

Output


2. Add if-else clauses

Jinja2 supports if-else conditions.

Jinja2 template

  • {% if <statement> %} to start
  • {% elif <statement> %} for else-if
  • {% else %} for else
  • {% endif %} to stop

Python script

Give a data of Alizabeth and see the result.

Output

Hmmm? The format is needed to fix. The "woman" appears not in same line.

Jinja2 template (fixed)

  • instead of {% ... %}, we have a dash inside as it turned out {%- ... %}. It will remove or trim spaces at the left.

Output (fixed)

Nice. It displays in a line properly.


3. Add loops

Jinja2 also supports iterations.

Jinja2 template

  • {% for <element> in <iterator> %} to start iteration.
  • {{ <element> }} or {{ <element>.<key>}} if dict.
  • {{ ... -}} to remove spaces at the right by having a right-handed dash.
  • {% else %} in case of no elements in the iterator.
  • {% endfor %} to end the iteration.

Python script

Output

If we supply data with no pets.

And if there is pets.


4. Refer other files

We can combine multiple Jinja2 template files as well.

Jinja2 template

  • {% include '<filepath>' %} to refer the target file.

Python script

We are using Jinja2.Environment(loader=Jinja2.FileSystemLoader("<folder_path>")).from_string(template).render(data). Otherwise, we would get an error TypeError: no loader for this environment specified.

Output


References