Templates

Jinja Templates

Creating Jinja Templates

Jinja templates define HTML with dynamic data in .jinja files.

Introduction to Jinja Templates

Jinja is a modern and designer-friendly templating engine for Python, modeled after Django's templates. It's used for rendering templates with dynamic data, making it a powerful tool for creating dynamic web applications. Jinja templates are typically saved with a .jinja extension and can be integrated with various web frameworks like Flask.

In this guide, we will explore the core features of Jinja templates, how to use them to inject dynamic data into HTML, and some useful examples to illustrate their functionality.

Basic Syntax and Placeholders

Jinja uses a simple syntax to embed dynamic content into static files. The most common elements are placeholders, expressions, and statements. Placeholders are enclosed in double curly braces {{ ... }} and are used to insert variable data into the template.

Here is a basic example of a Jinja template with placeholders:

In this example, {{ username }} and {{ balance }} are placeholders that will be replaced with the actual values passed to the template.

Control Structures

Jinja supports various control structures that allow you to iterate over data and include conditional logic in your templates. These structures are enclosed in curly braces and percentage signs {% ... %}.

Here's an example of using a for loop in a Jinja template:

This template will loop through a list called items and create a list item for each element. Similarly, you can use if statements to add conditionals:

In this example, the template checks if the user is authenticated and displays a personalized message if they are, or prompts them to log in if not.

Using Filters

Filters in Jinja allow you to transform variables and expressions at the template level, modifying the output directly. They are applied using the pipe character |.

Here is an example of using filters in a Jinja template:

This statement formats the today variable as a nicely formatted date string. Jinja comes with many built-in filters, such as length, upper, and lower, which allow you to perform common transformations easily.

Extending Templates

Jinja allows you to create reusable templates and extend base templates to maintain a consistent look and feel across your website. This is done using the extends and block directives, which will be covered in the next post in this series.