DEV Community

Tabish Javed
Tabish Javed

Posted on

Introduction to Jinja Template

Introduction

Jinja template is the most popular template engine for Flask and Django frameworks. It is used to make the templates in these frameworks dynamic and separate the backend from the frontend layer.

Installation

pip install jinja2
Enter fullscreen mode Exit fullscreen mode

Variables

In case of showing the value of a variable in the HTML code, we can use the following format.

<h1>Hello, {{ name }}!</h1>
Enter fullscreen mode Exit fullscreen mode

Expressions

Expressions can be evaluated in the HTML code and displayed using the following approach.

<p>{{ 2 + 2 }}</p>
<p>{{ 'Hello ' + 'World' }}</p>
<p>{{ 10 > 5 }}</p>
Enter fullscreen mode Exit fullscreen mode

Conditional Statements

You can add conditional statements and use them to display HTML code based on conditions being true or false.

{% if user %}
  <p>Hello, {{ user }}!</p>
{% else %}
  <p>Hello, Guest!</p>
{% endif %}
Enter fullscreen mode Exit fullscreen mode

Loops

Loops can be used in Jinja template to iterate through collections/lists of values and dynamically generate the elements as many times as required.

<ul>
  {% for fruit in fruits %}
    <li>{{ fruit }}</li>
  {% endfor %}
</ul>
Enter fullscreen mode Exit fullscreen mode

Inheritance

It is also possible to inherit the code from other templates and add additional code to it removing redundancy.

The following is a code which is base HTML code which can be inherited by all the files. We have created two blocks title and content and these will be replaced by HTML code of the files inheriting this base HTML.

# Base Template: templates/base.html
<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}{% endblock %}</title>
</head>
<body>
  <main>
    {% block content %}{% endblock %}
  </main>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

In the following code, the title block gets text Home Page and the content block gets an HTML code.

{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
  <h1>Welcome to our website!</h1>
  <p>Content goes here...</p>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)