Explain Codes LogoExplain Codes Logo

Get lengths of a list in a jinja2 template

jinja2
prompt-engineering
functions
best-practices
Alex KataevbyAlex Kataev·Jan 11, 2025
TLDR

To obtain the length of a list in a Jinja2 template, use the length filter:

{{ my_list|length }} // Magic in action ✨

This line will output the count of items in my_list. Neat, right?

But what if my_list is None? The server might burst into tears (read: throw an error). Let's prevent that:

{{ '0' if my_list is None else my_list|length }} // Because Null has feelings too 😢

If my_list is None, '0' will be displayed; otherwise, it generates the length of the list.

Different Scenarios to use length filter

Within loops

If you are inside a loop, Jinja2 provides loop.length:

{% for item in my_list %} {{ loop.index }} of {{ loop.length }} - {{ item }} // Who knew loops could count? 🎢 {% endfor %}

Index-based iteration

You can taste pythonic loops with range and length:

{% for i in range(my_list|length) %} Index {{ i }}: {{ my_list[i] }} // Because sometimes, we miss Python 🐍 {% endfor %}

Conditionally running code

Run code only if your list has elements:

{% if my_list|length > 0 %} We have {{ my_list|length }} items! // The more, the merrier 😊 {% else %} The list is empty. // Better luck next time 😔 {% endif %}

Visualization

Let's compare retrieving the length of a list in a Jinja2 template with a measuring tape:

Think of a measuring tape (📏) that we extend to measure various items.

Every element in the list is akin to an item on the tape (👕👖👗):

{% set clothes_list = ['shirt', 'pants', 'dress'] %} Number of clothes: {{ clothes_list|length }} // 3 is a crowd, and a complete outfit 😉

📏👕👖👗 (The tape measures 3 items: 🛍️📏 Length = 3)

Clear and illustrative, the tape measure directly shows the count!

Advanced Usage and Common Pitfalls

Dealing with more complex lists

If your list contains nested lists or objects, consider accessing their individual lengths:

{% for sublist in list_of_lists %} {{ loop.index }}: {{ sublist|length }} items // The length of each shop's shopping list {% endfor %}

Safe attribute navigation

Always check attribute existence before accessing it to avoid ruining your server’s day:

{{ (item.attribute if item.attribute is defined else [])|length }} // Don't run into walls 😉

Mind performance

While length is fine for most lists, with substantial ones, it might slow dance with your server's resources:

{{ 'Long list!' if my_list|length > 100 else 'Manageable List' }} // Be mindful of the long ones 😅