Blog Datasheets Home About me Clients My work Services Contact

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

  1. 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.

  2. Automatic HTML Escaping: It automatically escapes all variable content by default, which is important for security, preventing Cross-Site Scripting (XSS) attacks.

  3. Powerful and Flexible: Jinja2 provides control structures, such as loops and conditionals, inside the template, allowing for complex rendering logic.

  4. 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.

  5. Template Inclusion: Allows you to include one template within another.

Basic Syntax

Using Jinja2 in Flask

In Flask, Jinja2 is automatically integrated, and you render templates using the render_template function.

1
2
3
4
5
from flask import render_template

@app.route('/')
def index():
    return render_template('index.html', name='John Doe')

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.

Custom Filters

You can define custom filters in Flask. For instance:

1
2
3
@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

You can use this filter in a template like this:

1
{{ "hello" | reverse }}

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.


➡️ Getting Started with ESP32: A Comprehensive Guide


⬅️ Implementing a Simple Stepper Motor Control with AVR Atmega-328


Go back to Posts.