Jinja Arithmetic Expression: //
n
// operator in Jinja2 is an arithmetic operator that performs integer division. It divides the first number by the second and returns the truncated integer result, discarding any fractional part. This is useful when you need to know how many times one number fits into another without concern for the remainder. This behavior is consistent with the `//` operator in Python.nn
nn
How It Works
nThe `//` operator is exclusively used for performing integer division on numerical values. When Jinja2 encounters the expression number1 // number2, it performs the division and then discards the decimal part of the result. For example, `10 // 3` results in `3`, not `3.333…`. This is particularly useful for tasks like pagination, distributing items evenly, or counting full sets.n
Syntax
n
{{ number1 // number2 }}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use the // operator in a Jinja2 application.n
1. Simple Integer Division
nThis is a common use case for a pagination display where you need to calculate the total number of pages.nnJinja2 Templaten
{% set total_items = 45 %}n{% set items_per_page = 10 %}n<p>Number of full pages: {{ total_items // items_per_page }}</p>
nExplanation: The template divides `45` by `10`, resulting in a truncated integer of `4`. This tells you there are four full pages of items.nn
nn
2. Distributing Items Evenly
nThe `//` operator is great for distributing items into a certain number of groups.nnJinja2 Templaten
{% set students = 35 %}n{% set classrooms = 3 %}n<p>Each classroom gets {{ students // classrooms }} students.</p>
nExplanation: The template divides the number of students by the number of classrooms. The result is `11`, meaning each classroom gets 11 students, with the remainder being handled separately (in this case, 2 students would be left over).nn
nn
3. Using `//` with a `for` Loop
nYou can use the operator to perform integer division on each item within a loop, for example, to convert a price to a full dollar amount without cents.nnJinja2 Templaten
{% set products = [{ 'name': 'Shirt', 'price': 15.99 }, { 'name': 'Pants', 'price': 25.50 }] %}n<ul>n{% for product in products %}n <li>{{ product.name }}: Full price is ${{ product.price // 1 }}</li>n{% endfor %}n</ul>
nExplanation: This loop iterates through a list of products. For each product, it uses integer division by `1` to truncate the price, effectively removing the decimal part. The output will be a list showing the full dollar amount for each item.nn
n
