Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jinja

What are Jinja2 templates?

Adnan Abbas

Dynamic templates

In a scenario where we have an application that provides services to many users, we want some personalization for each user on the platform. Dynamic templates help us to serve a unique template containing the content corresponding to the user.

Example of dynamic templates

The figure above shows that a generic template is placed, containing a variable rule on the server-side. When this template is rendered on the client-side, an appropriate value is set instead of the rule. This new value is per the context of the application, i.e., information regarding the currently logged-in user. This kind of dynamic behavior of a template is called dynamic templating.

The Python framework Flask has inbuilt support for a dynamic templating engine known as Jinja.

Jinja

Jinja2 is a Python library that allows us to build expressive and extensible templates. It has special placeholders to serve dynamic data. A Jinja template file is a text file that does not have a particular extension. We will be using the .html extension with the template files because they will also include HTML syntax.

Usage

We use Flask’s render_template() method to render a Jinja2 templated HTML page at the specified route. For example:

from flask import render_template
from app import app

@app.route('/')
def home():
    return render_template("home.html")

Delimiters

Here are some delimiters that are used in the Jinja syntax:

  • {% ... %} is used for statements.
  • {{ ... }} is used for variables.
  • {# ... #} is used for comments.
  • # ... ## is used for line statements.

Variables

Flask allows us to pass any Python object to the template, which can then be referred to inside the template using Jinja syntax.

We can use variables inside the templates by following these two steps:

  • The object is provided as a named argument to the render_template() function.
return render_template("index.html", my_object = Object)
  • The value of this object is then fetched inside the template (index.html) using the {{}} syntax.
{{ my_object }}

Loops

The syntax of for loops in Jinja is very similar to Python:

{% for elements in array %}
    ...
{% endfor %}

You must always end the for loop with {% endfor %}.

Conditionals

Like loops, we can also add conditional statements in the template. This is how we can do it:

{% if true %}
{% endif %}

You must always end the if block with {% endif %}.

For multiple branches of conditions, elif and else can be used.

{% if ... %}
{% elif ... %}
{% else %}
{% endif %}

To learn more about the features offered by Jinja, you can read the official documentation here.

RELATED TAGS

jinja

CONTRIBUTOR

Adnan Abbas
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring