Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 72 ยท Templates with Jinja

Loops and Conditionals in Templates

Learn Jinja control flow in Flask templates: for loops with the loop variable, for-else for empty lists, if/elif/else, whitespace control and reusable macros.

A template that only prints variables can't show a list of articles or hide an admin link from ordinary users. For that, Jinja has statements: {% for %} repeats markup, and {% if %} chooses between alternatives. They look a lot like Python, with closing tags such as {% endfor %} instead of indentation.

In this lesson you'll loop over lists and dictionaries, use the special loop variable for numbering and separators, handle empty lists elegantly, branch with if, clean up stray whitespace in the output, and package repeated markup into a macro.

The for loop

HTML
<ul>
{% for article in articles %}
  <li>{{ article.title }}</li>
{% endfor %}
</ul>

The loop variable (article) only exists inside the block. Anything you can iterate in Python works: lists, tuples, dictionaries (use .items(), .keys() or .values()), query results, generators. You can also filter inline with a condition, {% for a in articles if a.published %}, and unpack tuples, {% for name, score in scores.items() %}.

Inside a loop Jinja gives you a loop object with useful properties:

Variable Meaning
loop.index Current iteration, counting from 1
loop.index0 Current iteration, counting from 0
loop.first, loop.last True on the first / last pass
loop.length Total number of items
loop.revindex Iterations left, counting down to 1
loop.cycle(a, b) Alternate between the given values
Python Looping with the loop variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The separator pattern {{ ", " if not loop.last }} is the standard trick for comma-separated lists: print the comma after every item except the last. (For plain strings, the join filter, {{ authors | join(", ") }}, is shorter.)

Jinja has no break or continue by default. If you need to skip items, filter them in the loop header (for x in xs if ...) or, better, prepare the list in the view before rendering.

for ... else: the empty list

A very common need: show the items, or a friendly message if there are none. Jinja's {% else %} on a for loop runs only if the sequence was empty.

flowchart TD
    A["{% for item in items %}"] --> B{"items empty?"}
    B -->|no| C["render body once per item"]
    B -->|yes| D["render the {% else %} block"]
    C --> E["{% endfor %}"]
    D --> E

The else block of a loop is a built-in "nothing to show" case.

if, elif and else

Conditions use the same operators as Python: ==, !=, <, >=, and, or, not, in. Truthiness follows Python too, so an empty list, an empty string, 0 and None are all false. Jinja adds tests written with is: is defined, is none, is divisibleby(3), is even, is string.

Python if, elif, else and for-else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A tidy rule: put decisions that depend on data in templates (show or hide), but put decisions about what the data is in the view (is the user allowed to do this?). Hiding a button is a convenience, not security. The server must still check permission, as in Roles and Permissions.

Controlling whitespace

Jinja leaves the newlines and spaces around tags in the output. Browsers collapse most whitespace in HTML, so it usually doesn't matter, but it does in <pre> blocks, emails, plain-text output and tests. Two tools help:

  • A minus sign next to a delimiter strips whitespace on that side: {%- ... %} removes whitespace before the tag, {% ... -%} removes whitespace after it. This works for {{ -}} as well.
  • Flask enables no global trimming, but a Jinja environment can set trim_blocks (removes the first newline after a block tag) and lstrip_blocks (strips leading spaces before a block tag). Flask does not turn them on, so the minus signs are your main tool.

You already saw both in the examples above, where -%} kept each loop iteration on its own tidy line.

Macros: functions for markup

Repeating the same piece of HTML in many places is a sign you need a macro. A macro is like a Python function that returns a string of markup. You define it with {% macro %} and call it like a function.

Python A macro for repeated markup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Macros accept positional and default arguments, can call each other, and their output is treated as safe markup, so values passed into them are still escaped (see the <Chair> row). Macros defined in one file can be imported into another with {% from "macros.html" import badge %}; we do that in Template Inheritance and Includes.

Variables inside blocks

{% set total = 0 %} creates a variable, but a loop has its own scope: assigning to a name inside a for doesn't change the outer variable. To accumulate, compute in the view, or use a filter such as sum(attribute="price"):

HTML
Total: {{ items | sum(attribute="price") }}

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tag closes a {% for %} block?

    Every Jinja block statement has a matching endfoo tag; for closes with endfor.
  2. 2. What does loop.index start counting from?

    loop.index starts at 1; use loop.index0 for zero-based counting.
  3. 3. When does the {% else %} block of a for loop run?

    for-else is Jinja's way to show a 'nothing here' message.
  4. 4. What does the minus in {% endfor -%} do?

    A minus inside the delimiter trims whitespace on that side of the tag.
  5. 5. How do you print comma-separated values with no comma after the last one inside a loop?

    Print the separator after each item except the last. The join filter is an alternative for plain lists.

Summary

  • {% for x in xs %}...{% endfor %} repeats markup; use .items() for dictionaries and for x in xs if cond to filter.
  • The loop object offers index, index0, first, last, length, revindex and cycle().
  • {% else %} on a loop handles the empty case.
  • if / elif / else use Python-like operators and truthiness, plus tests such as is defined and is none.
  • A minus sign in {%- -%} trims whitespace; macros package repeated markup into callable pieces.
  • Loop variables are scoped to the loop; compute totals in the view or with filters.

Next: Template Inheritance and Includes, sharing one layout across every page.