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
Variables
In case of showing the value of a variable in the HTML code, we can use the following format.
<h1>Hello, {{ name }}!</h1>
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>
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 %}
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>
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>
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 %}
Top comments (0)