Post

Let's try: Jinja2

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

Let's try: Jinja2

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.

And we can begin.


1. Put into a string

Start from writing variables into a 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.
  • Using this to render a substituted string.

    1
    2
    3
    
    from jinja2 import Template
    
    Template(template).render(data)
    
  • string


2. Add if-else clauses

Jinja2 supports if-else conditions.

    • {% if <statement> %} to start
    • {% elif <statement> %} for else-if
    • {% else %} for else
    • {% endif %} to end
  • Give a data of Alizabeth and see the result.

    ifelse

Error spotted !
Look at the output above. The “woman” appears not in same line.
Below is the fix.

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

  • Nothing needed to be changed here.

  • ifelse fix

    Nice. It displays in a line properly.


3. Add loops

  • Jinja2 also supports iterations.

    • {% 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.
  • If we supply data with no pets.

    loop no pets

    And if there is pets.

    loop pets


4. Refer other files

We can combine multiple Jinja2 template files as well.

    • {% include '<filepath>' %} to refer the target file.
  • We are using code below or would get an error TypeError: no loader for this environment specified.

    1
    2
    3
    
    from jinja2 import Environment, FileSystemLoader
    
    Environment(loader=FileSystemLoader("<folder_path>")).from_string(template).render(data)
    
  • ref


References

This post is licensed under CC BY 4.0 by the author.