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.
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:
for LoopsIterate over lists, tuples, dictionaries, and database querysets:
{% else %}Jinja2 provides a built-in else block inside for loops that renders when the collection is empty:
loop VariableInside 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') |
{% 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?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Jinja2 Syntax, Variables & Custom Filters | Template Inheritance & Layout Composition |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.