Jinja Special Loop Variable: loop.cycle
n
for loop, the loop.cycle helper is a powerful tool for alternating between a set of values with each iteration. This is particularly useful for applying different CSS classes to a series of elements, a technique often called “zebra-striping.” Using `loop.cycle` helps you create visually distinct rows in a table or list without needing to manually check the iteration number.nn
nn
n
How It Works
nThe loop.cycle function takes a variable number of arguments (e.g., strings, numbers, or even variables). In each loop iteration, it returns the next value from this sequence. When it reaches the end of the sequence, it “cycles” back to the beginning for the next iteration. This allows you to apply a repeating pattern to your template elements. For instance, loop.cycle(‘odd’, ‘even’) will return `’odd’`, then `’even’`, then `’odd’` again, and so on.nnSince Jinja 2.1, a more advanced feature called loop-unbound cycling was introduced. This allows you to create a `cycler` object outside of a `for` loop and use its `.next()` method to get the next value whenever you need it, giving you more control over the cycling process.n
Syntax
n
{% for item in items %}n <!-- The value of loop.cycle will alternate for each loop -->n <div class="{{ loop.cycle('class1', 'class2') }}">{{ item }}</div>n{% endfor %}
nn
nn
Demonstration with Code Samples
n
1. Basic Zebra-Striping for a List
nThis is a classic use case for `loop.cycle`, where you apply alternating classes to list items to make them easier to read. The example below shows how to use `loop.cycle` to apply `odd` and `even` classes to list items.nnJinja2 Templaten
{% set rows = ['Item 1', 'Item 2', 'Item 3', 'Item 4'] %}n<ul>n{% for row in rows %}n <li class="{{ loop.cycle('odd-row', 'even-row') }}">{{ row }}</li>n{% endfor %}n</ul>
nExplanation: The `for` loop iterates over the `rows` list. In the first iteration, `loop.cycle` returns `’odd-row’`, in the second it returns `’even-row’`, and it continues to alternate between these two values, which you can then style with CSS.n
2. Alternating Background Colors in a Table
nTables are another ideal use case for `loop.cycle` to improve readability. This example shows how to use two different CSS classes to create a subtle alternating background color effect for a list of users.nnJinja2 Templaten
{% set users = ['Alice', 'Bob', 'Charlie', 'David'] %}n<table>n <tr><th>User</th></tr>n
n n
n {% for user in users %}n <tr class="{{ loop.cycle('bg-gray-100', 'bg-white') }}">n <td>{{ user }}</td>n </tr>n {% endfor %}n
n</table>n
nExplanation: As the loop processes each `user`, the `loop.cycle` function alternates between the `’bg-gray-100’` and `’bg-white’` class names. This allows you to apply different background colors to successive table rows, making the table visually appealing and easier to scan.nn
n
