G2Labs Grzegorz Grzęda
A primer on Jinja2
April 11, 2024
Jinja2 is a popular template engine for Python, often used with web frameworks like Flask. It allows for dynamic generation of HTML, XML, or other types of files by combining a template with a data source. Jinja2 is powerful, flexible, and easy to use, making it an ideal choice for web application development.
Key Features of Jinja2
Template Inheritance: Jinja2 supports template inheritance, which allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.
Automatic HTML Escaping: It automatically escapes all variable content by default, which is important for security, preventing Cross-Site Scripting (XSS) attacks.
Powerful and Flexible: Jinja2 provides control structures, such as loops and conditionals, inside the template, allowing for complex rendering logic.
Filters and Custom Filters: You can use filters to modify variables in the template. Jinja2 comes with many built-in filters and allows you to add custom filters.
Template Inclusion: Allows you to include one template within another.
Basic Syntax
Variables: Use
{{ ... }}
to print the value of a variable or expression.1
<p>Hello, {{ name }}!</p>
Control Structures: Jinja2 supports loops and conditionals.
Template Inheritance: The
extends
andblock
tags are used for inheritance.Filters: Use filters to modify variables.
1
{{ "hello" | capitalize }}
Using Jinja2 in Flask
In Flask, Jinja2 is automatically integrated, and you render templates using the render_template
function.
This will render the index.html
template and pass the name
variable to it.
Template Inheritance
A common pattern in using Jinja2 with Flask is to create a base template (like base.html
) that includes your site’s layout. Then, individual pages extend this base template and override specific sections.
base.html:
home.html:
Custom Filters
You can define custom filters in Flask. For instance:
You can use this filter in a template like this:
|
|
Conclusion
Jinja2 is a powerful tool for rendering templates in Python web applications. Its integration with Flask makes it simple to generate dynamic web pages. By understanding Jinja2’s syntax and features, you can create more maintainable and secure web applications. Template inheritance, in particular, helps in creating a consistent layout across different pages of a web application.