Skip to content

Control Structures (If/Else, Loops)

Control structures are how you build dynamic pages.

If / elif / else

{% if user %}
  <p>Hello, {{ user.username }}!</p>
{% elif guest_name %}
  <p>Hello, {{ guest_name }}!</p>
{% else %}
  <p>Hello, stranger!</p>
{% endif %}
{% if user %}
  <p>Hello, {{ user.username }}!</p>
{% elif guest_name %}
  <p>Hello, {{ guest_name }}!</p>
{% else %}
  <p>Hello, stranger!</p>
{% endif %}

For loops

<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>
<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

Loop helpers

Jinja provides looploop inside loops:

  • loop.indexloop.index (1-based)
  • loop.index0loop.index0 (0-based)
  • loop.firstloop.first, loop.lastloop.last
{% for user in users %}
  <p>{{ loop.index }}. {{ user.username }}</p>
{% endfor %}
{% for user in users %}
  <p>{{ loop.index }}. {{ user.username }}</p>
{% endfor %}

Handling empty lists

{% if users %}
  <!-- show list -->
{% else %}
  <p>No users found.</p>
{% endif %}
{% if users %}
  <!-- show list -->
{% else %}
  <p>No users found.</p>
{% endif %}

Keep logic light

Prefer to compute complex values in Python and pass them in.

Templates should be readable.

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did