Examples
Jinja Loop Template
Rendering a Loop Template
Jinja loop template iterates a list with {% for %}.
Introduction to Jinja Loop Template
Jinja is a powerful templating engine for Python, often used in web frameworks like Flask. One of its core features is the ability to iterate over lists using the {% for %} loop. This allows developers to dynamically render list data in HTML templates, making it a versatile tool for web applications.
Basic Syntax of the {% for %} Loop
The basic syntax of a Jinja loop is straightforward. Here is the general structure:
{% raw %}{% for item in list %} ... {% endfor %}{% endraw %}
In this structure, item
represents the current element in list
that the loop is iterating over. The {% endfor %}
tag marks the end of the loop block.
Rendering a List of Items
To render a list of items, such as a list of fruits, you can use the following example. Assume you have a list of fruits defined in your Python application:
fruits = ['Apple', 'Banana', 'Cherry']
In your Jinja template, you can use the {% for %} loop to iterate over this list and render each fruit as a list item in HTML:
Using Loop Variables
Jinja provides some special variables that are available within a {% for %} loop to give you more control and information about the current iteration:
- loop.index: The current iteration of the loop (1-indexed).
- loop.index0: The current iteration of the loop (0-indexed).
- loop.revindex: Number of iterations from the end (1-indexed).
- loop.revindex0: Number of iterations from the end (0-indexed).
- loop.first: True if first iteration.
- loop.last: True if last iteration.
- loop.length: The total number of items in the sequence.
Loop Control Statements
Within Jinja loops, you can use control statements like {% if %} to conditionally render content. This is useful for filtering items or applying specific styles to certain elements:
Conclusion
Jinja's {% for %} loop is a fundamental tool for iterating over lists and rendering dynamic content in templates. By mastering the loop's syntax and features, such as loop variables and control statements, you can create highly flexible and efficient web applications.
Examples
- Previous
- Form Template
- Next
- Conditional Template