Jinja2 Arithmetic Expression: % (Modulo)
n
% operator in Jinja2 is an arithmetic operator that calculates the remainder of an integer division. It is also known as the modulo operator. This is a fundamental tool for various tasks in templating, such as determining if a number is even or odd, creating a checkerboard pattern, or cycling through a list of items. Its behavior is consistent with the % operator in Python.nn
nn
How It Works
nThe % operator returns the remainder when one number is divided by another. When Jinja2 evaluates the expression number1 % number2, it performs the division and returns the integer that is left over. For example, `10 % 3` results in `1`, because 10 divided by 3 is 3 with a remainder of 1.n
Syntax
n
{{ number1 % number2 }}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use the % (modulo) operator in a Jinja2 application.n
1. Checking for Even or Odd Numbers
nA common use case for the modulo operator is to determine if a number is even or odd by checking if the remainder after dividing by 2 is 0.nnJinja2 Templaten
{% set number = 7 %}n{% if number % 2 == 0 %}n <p>The number {{ number }} is even.</p>n{% else %}n <p>The number {{ number }} is odd.</p>n{% endif %}
nExplanation: The template divides `7` by `2`. The remainder is `1`. Since `1` is not equal to `0`, the `else` block is rendered, stating that the number is odd.nn
nn
2. Creating a Checkerboard Pattern in a Loop
nYou can use the modulo operator within a for loop to apply different styling to alternating items.nnJinja2 Templaten
<ul>n{% for item in range(1, 6) %}n {% if loop.index % 2 == 0 %}n <li style="background-color: #eee;">Item {{ loop.index }}</li>n {% else %}n <li style="background-color: #fff;">Item {{ loop.index }}</li>n {% endif %}n{% endfor %}n</ul>
nExplanation: This loop iterates from 1 to 5. The `loop.index` variable is a special variable that holds the current iteration number (starting from 1). The `if` statement checks if the index is evenly divisible by 2. If it is, the item gets a grey background; otherwise, it gets a white background, creating a striped pattern.nn
nn
3. Cycling Through a List
nThe modulo operator is useful for cycling through a limited set of items, such as a list of colors or icons, for a larger number of iterations.nnJinja2 Templaten
{% set colors = ['red', 'green', 'blue'] %}n<ul>n{% for item in range(1, 10) %}n {% set color_index = (loop.index - 1) % 3 %}n <li style="color: {{ colors[color_index] }}">Item {{ loop.index }}</li>n{% endfor %}n</ul>
nExplanation: The `color_index` is calculated by taking the current `loop.index` (minus 1 to make it zero-based) and finding its remainder when divided by the length of the `colors` list (`3`). This ensures that the index will always be 0, 1, or 2, allowing the loop to cycle through the colors repeatedly.nn
