Basics

Jinja Loops

Loop Structures

Jinja loops use {% for %} to iterate lists or dictionaries.

Introduction to Jinja Loops

Jinja is a powerful templating engine for Python. It allows developers to generate dynamic HTML content by embedding Python-like expressions within templates. One of the key features of Jinja is its ability to loop over lists and dictionaries using the {% for %} statement. This post will guide you through the basic usage of Jinja loops with practical examples.

Looping Through Lists

Jinja loops are often used to iterate over lists, making it easy to generate repetitive HTML structures. Here's a simple example:

In this example, fruits is a list that contains the names of different fruits. The {% for %} loop will iterate over each fruit in the list and render a <li> element for each one.

Looping Through Dictionaries

Jinja also allows you to loop through dictionaries. You can access both the keys and values in each iteration. Here's how you might loop over a dictionary:

In this example, user_info is a dictionary with keys and values representing user attributes. The loop iterates over the dictionary and prints each key-value pair in a paragraph.

Using Loop Variables

Jinja provides special variables within loops that give you more control over the iteration process. These variables include loop.index, loop.index0, loop.revindex, loop.revindex0, loop.first, loop.last, and loop.length. Here's an example of using some of these variables:

In this snippet, loop.index is used to display the current iteration count starting from 1. The loop.last variable checks if the current item is the last in the list, appending "(last item)" if true.

Nested Loops

Jinja supports nested loops, which can be useful when dealing with complex data structures. Here's an example of a nested loop:

In this case, product_categories is a dictionary where each key is a product category, and the value is a list of products in that category. The outer loop iterates over the dictionary, while the inner loop iterates over each list of products.

Conclusion

Jinja loops are a powerful tool for generating dynamic content in templates. By understanding how to use {% for %} to iterate over lists and dictionaries, you can create more complex and flexible templates. Experiment with the examples provided to see how Jinja loops can be applied to your own projects.

Previous
Case