Sling Academy
Home/FastAPI/How to use loops in Jinja

How to use loops in Jinja

Last updated: November 28, 2024

Introduction to Loops in Jinja

Jinja is a modern and designer-friendly templating language for Python, modeled after Django's templates. It is easy to learn and adaptable to various backend frameworks. A core feature of Jinja is the ability to use loops and iterate over data structures. In this article, we'll explore how to use loops in Jinja templates with clear examples.

Basic Loop Syntax

Jinja uses familiar syntax to Python developers. To create a loop in Jinja, you use the for statement inside a template.

{% for item in list %}
    {{ item }}
{% endfor %}

In this example, list is a sequence like a list or a tuple, and item is the variable that represents each element on each iteration of the loop.

Example with Simple List

Let's expand on the basic example with a concrete implementation:

from jinja2 import Template

# Our data
items = ["apple", "banana", "cherry"]

# Our template
template = Template("""
{{ item }}""")

# Render the template with the data
rendered = template.render(items=items)
print(rendered)

When you run this Python code, it will output:

<ul>
    <li>apple</li>
    <li>banana</li>
    <li>cherry</li>
</ul>

Looping Over a Dictionary

Jinja allows you to loop over a dictionary, where you can use both keys and values.

{% for key, value in dictionary.items() %}
    {{ key }}: {{ value }}
{% endfor %}

Here's how you might implement it with data:

# Our data
dictionary = {"name": "John", "age": 25, "city": "New York"}

# Our template
template = Template("""
{{ key }}: {{ value }}""")

# Render the template with the data
rendered = template.render(dictionary=dictionary)
print(rendered)

And this will produce:

<ul>
    <li>name: John</li>
    <li>age: 25</li>
    <li>city: New York</li>
</ul>

Using Loop Variables

Jinja provides several special variables within loop constructs:

  • loop.index: The current iteration of the loop (1 indexed)
  • loop.index0: The current iteration of the loop (0 indexed)
  • loop.revindex: The number of iterations from the end (1 indexed)
  • loop.revindex0: The number of iterations from the end (0 indexed)
  • loop.first: True if current iteration is the first
  • loop.last: True if current iteration is the last
{% for item in list %}
    {% if loop.first %}
        First: {{ item }}
    {% elif loop.last %}
        Last: {{ item }}
    {% else %}
        {{ item }} is at position {{ loop.index }}
    {% endif %}
{% endfor %}

Conclusion

Loops in Jinja provide a powerful way to iterate over sequences and can be combined with conditional statements to build dynamic content templates. By using the examples above, you can get started with creating efficient, dynamic templates in Jinja.

Next Article: How to use if/ else in Jinja

Series: Jinja Templates

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict
  • Resolving the FastAPI Circular References Error