Jinja’s sequence Test: Handling Iterables
nThe Jinja sequence test is a versatile and fundamental tool for checking if a variable is a sequence, which in Jinja’s context means it’s an iterable object. This test returns True for variables that can be iterated over, such as lists, tuples, and strings, but False for single, non-iterable values like integers or booleans. It is a critical component for writing robust and flexible templates, as it allows you to safely loop over data, prevent errors, and adapt your template logic based on the data structure you’re working with.nn
nn
How the sequence Test Works
nThe syntax for the sequence test is straightforward: value is sequence.nnThis expression checks the variable’s underlying type to determine if it’s an iterable. It’s a broad check that covers all common Python sequence types, but it’s important to understand what it includes and excludes.nnThe sequence test returns True for:n
- n
- Lists:
[1, 2, 3] - Tuples:
('a', 'b', 'c') - Strings:
'hello'(a string is an iterable of its characters) - Dictionaries:
{'key': 'value'}(a dictionary is an iterable of its keys) - Sets:
{'a', 'b', 'c'}
n
n
n
n
n
nThe sequence test returns False for:n
- n
- Integers:
123 - Floats:
3.14 - Booleans:
TrueorFalse None
n
n
n
n
nHere’s a basic example demonstrating its usage:n
{% set my_list = [1, 2, 3] %}n{% set my_string = "hello" %}n{% set my_number = 42 %}nn{% if my_list is sequence %}n <p>This is a sequence. It has {{ my_list|length }} items.</p>n{% endif %}nn{% if my_string is sequence %}n <p>"{{ my_string }}" is also a sequence. It has {{ my_string|length }} characters.</p>n{% endif %}nn{% if my_number is sequence %}n <p>This will not show because numbers are not sequences.</p>n{% endif %}
nIn this snippet, both the list and the string pass the sequence test, while the number does not. This demonstrates how sequence is used to confirm if a variable is suitable for looping or for use with filters that operate on iterables, such as the length filter.nn
nn
sequence Test vs. iterable Test
nThe terms “sequence” and “iterable” are often used interchangeably in Jinja’s documentation and within the community. The sequence test is essentially an alias for the iterable test, and for all practical purposes, they function identically. When you encounter either test, you can assume it’s checking for the same behavior: can the object be looped over?nnHowever, for clarity and historical consistency, it’s good to know that sequence is one of the more common and explicit ways to phrase this check in your templates.nn
nn
Practical Applications of the sequence Test
nThe sequence test is invaluable in scenarios where data structures can vary, especially when receiving data from an API, a database, or user input.n
1. Safely Looping Over Variables
nThe primary use case for the sequence test is to ensure that a variable is a list, tuple, or another iterable before attempting to use a for loop. Trying to loop over a non-iterable will cause a template error.n
{% set comments = product.comments or none %}nn{% if comments is sequence %}n <ul>n {% for comment in comments %}n <li>{{ comment }}</li>n {% endfor %}n </ul>n{% else %}n <p>No comments available.</p>n{% endif %}
nIn this example, if product.comments is a list, the loop runs. If it’s None (or any other non-sequence), the else block is executed, preventing an error and providing a user-friendly message.n
2. Conditional Rendering and Formatting
nYou can use the sequence test to conditionally render content or apply formatting based on the data type. This is useful for displaying lists of tags, but not displaying the tag container if the list is empty or not a list at all.n
{% if user.tags is sequence and user.tags %}n <div class="user-tags">n {% for tag in user.tags %}n <span class="badge">{{ tag }}</span>n {% endfor %}n </div>n{% endif %}
nHere, the if statement checks for both is sequence and truthiness (i.e., not an empty list), providing a robust way to only render the tag container when it’s appropriate.n
3. Default Values
nThe sequence test can be used to set a default value for a variable if it’s not a sequence, ensuring subsequent logic that relies on an iterable can proceed without issue.n
{% set my_list = some_variable %}n{% if my_list is not sequence %}n {% set my_list = [] %}n{% endif %}nn{# Now my_list is guaranteed to be a list or tuple #}n{% for item in my_list %}n ...n{% endfor %}
nThis is a clean way to normalize data types before performing operations on them.nn
nn
Conclusion
nThe Jinja sequence test is a foundational component for building flexible, robust, and error-resistant templates. By allowing you to check if a variable is an iterable, it prevents crashes from invalid loop attempts and empowers you to write dynamic logic that gracefully adapts to different data structures. Whether you are consuming external data, handling user input, or simply ensuring your loops are safe, the sequence test is a simple and effective way to ensure your templates behave correctly and reliably.
