Jinja Control Structure: The for/else Block
n
nn
n
How It Works
nUnlike Python, where an `else` block is executed if a loop completes without hitting a `break` statement, Jinja’s `else` block is specifically designed to handle cases where the loop never runs. The template engine first checks the sequence to be iterated. If the sequence is empty, the entire `for` block is skipped, and the code within the `else` block is rendered instead. This is a very predictable and reliable way to handle empty data gracefully in your templates.n
Syntax
n
{% for item in sequence %}n <!-- Code to render for each item -->n{% else %}n <!-- Code to render if the sequence is empty -->n{% endfor %}
nn
nn
n
Demonstration with Code Samples
n
1. Handling an Empty List
nThis is the most common use case for the `else` block, where you want to display a message when a list of items is empty. The example below shows how to display a “no users found” message when the `users` list is empty.nnJinja2 Templaten
{% set users = [] %}n<ul>n{% for user in users %}n <li>{{ user.username|e }}</li>n{% else %}n <li><em>no users found</em></li>n{% endfor %}n</ul>
nExplanation: Since the `users` list is an empty array, the `for` loop is never entered. The Jinja engine proceeds directly to the `else` block, which then renders the “no users found” message inside a list item.nn
nn
n
2. Handling a Filtered-Out List
nThe `else` block also works perfectly with conditional filtering. If your filter removes every item from the sequence, the `else` block will be executed.nnJinja2 Templaten
{% set products = [n {'name': 'Laptop', 'in_stock': false},n {'name': 'Mouse', 'in_stock': false}n] %}n<ul>n{% for product in products if product.in_stock %}n <li>{{ product.name|e }}</li>n{% else %}n <li><em>no products currently in stock</em></li>n{% endfor %}n</ul>
nExplanation: The `for` loop with the `if product.in_stock` filter checks both items in the `products` list. Since both items have `in_stock: false`, the filter removes them, and the loop never iterates. As a result, the `else` block is executed, displaying the “no products currently in stock” message.nn
n
