Control Structures, Loops & Conditionals
Control Structures, Loops & Conditionals in Jinja2
Dynamic web pages require conditional branching and iterative rendering. Jinja2 provides robust control structures enclosed within {% ... %} blocks, including if/elif/else conditions and feature-rich for loops.
1. Conditionals (if, elif, else)
Jinja2 conditionals mirror Python's logical evaluation rules, checking for truthy and falsy values:
You can combine conditions with boolean operators and, or, not, and identity checks is defined, is none:
2. Iteration with for Loops
Iterate over lists, tuples, dictionaries, and database querysets:
Empty List Handling with {% else %}
Jinja2 provides a built-in else block inside for loops that renders when the collection is empty:
3. The Special loop Variable
Inside every {% for %} loop, Jinja2 provides an automatic loop context variable containing execution metadata:
| Variable | Type | Description |
|---|---|---|
loop.index | int | 1-based iteration counter (1, 2, 3...) |
loop.index0 | int | 0-based iteration counter (0, 1, 2...) |
loop.revindex | int | Iterations remaining until the end (1-based) |
loop.first | bool | True during the first iteration |
loop.last | bool | True during the final iteration |
loop.length | int | Total number of items in the iterable sequence |
loop.cycle | method | Alternate between arguments: loop.cycle('odd', 'even') |
Practical Example: Zebra-Striped Tables & Badges
Practice Quiz
{% for %} loop without requiring a separate if check?loop.index during the very first iteration of a Jinja2 loop?user_bio is explicitly defined in the template context?{% if %} conditional block be terminated in Jinja2?Template Inheritance & Layout Composition
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Jinja2 Syntax, Variables & Custom Filters | Template Inheritance & Layout Composition |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.