---
title: '{% for %}'
description: for loop.
date: '2026-08-02'
categories:
  - Template Tag
  - Logic
canonical: https://coolify.djangotemplatetagsandfilters.com/tags/for/
doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#for
---

# {% for %}

for loop.

## Documentation

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

### Looping through a Queryset

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

### Looping through a Dictionary

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

### Looping through a List

```django
<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

```django
<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:

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

### Looping through a List displaying a Counter

```django
<table>
  {% for fruit in fruits %}
    <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ fruit }}</td>
    </tr>
  {% endfor %}
</table>
```

### 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.first` – `True` for the first iteration.
6. `forloop.last` – `True` for the last iteration.
7. `forloop.length` – The total number of items in the sequence. **New in Django 6.0.**
8. `forloop.parentloop` – The current loop’s parent loop.

## Commentary

Also see the [`ifchanged`](/tags/ifchanged/) tag, and [`{% for … empty %}`](/tags/for-empty/) for handling an empty iterable.
