Introduction
Jinja is a templating language for Python. It is used to generate dynamic content in web applications. It provides Python-like expressions inside HTML templates to generate content dynamically, rendered by the server. Official Documentation
Installation
Flask
Jinja is included in the Flask framework, so it is not necessary to install it separately.
Delimiters
- {% … %} for Statements
- {{ … }} for Expressions
- {# … #} for Comments
Template Inheritance
File structure
templates/
base.html
home.html
Simple Inheritance
base.html
Example of a base template for html pages
home.html
Using the base template and overwriting the “content” block
Abstract Base Template
base.html
base template for html pages, in which it must be overriden, but not necessairily by the direct child template, cannot be rendered directly
Template Inclusion
Conditional
If Statement
The if
statement is used to check if a condition is true. It can be followed by an elif
statement to check additional conditions, and an else
statement to execute code when no conditions are met.
Control Structures
For loop in list
The for
loop is used to iterate over a list of items. It can be used to generate HTML elements dynamically.
For loop in dict
Text Escaping
Adding |safe does automatic escaping of the content of the variable, useful for rendering HTML content from a variable when it is known to be safe and not untreated user-generated content.
Endpoint URL
Generate dynamic URLs for endpoints. It is useful to decouple the URL from the endpoint name, thus making it easier to change the URL in the future.
Usage
app.py
template.html
It is generating the login
and register
URLs based on the function names in the app.py
file.
Static files
The url_for
function can be used to generate the URL for static files like CSS, JS, and images. To do this, the static
folder must be created in the project root directory.
In this example, the global.css
file is located in the styles/shared
folder inside the static
folder.
Macros
Macros are reusable code blocks that can be called multiple times with different parameters. They are useful for generating repetitive content in templates.
Declaration
macro.html
In this example, the macro my_macro
takes two parameters: parameter_1
and parameter_2
. It generates a div
element with the content of the parameters. The parameter_1
is an object with a name
attribute, and the parameter_2
is a list of items.
Usage
The from
statement imports the macro from the macro.html
file. The my_macro
function is then called with the specified parameters.
Call With Children
When a macro is called with children, the content inside the call block is passed to the macro as the caller
function.