for Tag

Logic Most Useful

Documentation

Often used to loop through querysets, but it can be used to loop through any iterable.

Looping through a Queryset

<ul>
  {% for joke in joke_list %}
    <li>{{ joke.question }}</li>
  {% endfor %}
</ul>

Looping through a Dictionary

<ol>
  {% for item, remaining in inventory.items %}
    <li>{{ item }}: {{ remaining }}</li>
  {% endfor %}
</ol>

Looping through a List

<ol>
  {% for fruit in fruits %}
    <li>{{ fruit }}</li>
  {% endfor %}
</ol>

To loop through a list in reverse order, used reversed:

Looping through a List in Reverse

<ol>
  {% for fruit in fruits reversed %}
    <li>{{ fruit }}</li>
  {% endfor %}
</ol>

Empty Iterables

Sometimes, you won’t be sure that your iterable contains any values. This is especially true with querysets. In such case, you can use the empty tag to output a message indicating that no records were found. For example:

<ul>
  {% for joke in joke_list %}
    <li>{{ joke.question }}</li>
  {% empty %}
    <li>Sorry, there are no jokes.</li>
  {% endfor %}
</ul>

Variables Available in for Loops

The following variables are available within for loops:

  1. forloop.counter – The current iteration starting with 1.
  2. forloop.counter0 – The current iteration starting with 0.
  3. forloop.revcounter – The iteration’s position from the end. For the last iteration, this will be 1.
  4. forloop.revcounter0 – The remaining iterations. For the last iteration, this will be 0.
  5. forloop.firstTrue for the first iteration.
  6. forloop.lastTrue for the last iteration.
  7. forloop.parentloop – The current loop’s parent loop.

Did we get something wrong? Is there a use case for the for tag that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Sept. 16, 2020, 7:33 p.m. EST