Finding the Largest Item with Jinja max Filter
nThe Jinja max filter is used to find the largest item in a sequence, such as a list of numbers or strings. It’s the opposite of the min filter and is great for tasks like finding the highest price, the latest date, or the largest value in a set of data.nn
nn
How It Works
nThe max filter takes a sequence as input and returns the largest item. The comparison is straightforward for numbers, but for strings, it’s based on alphabetical order. If the sequence is empty, the filter returns an Undefined object.nnThe basic syntax is {{ my_list | max }}.nnYou can also customize the filter’s behavior using two optional parameters:n
- n
case_sensitive: A boolean (defaultFalse) for string comparisons. WhenTrue, uppercase letters are considered smaller than lowercase letters. WhenFalse, the comparison is case-insensitive.attribute: A string or integer (defaultNone) that lets you find the object with the maximum value for a specific attribute. For example, in a list of product dictionaries, you can find the product with the highest price.
n
n
nn
nn
Practical Examples
nHere are some practical examples to show you how the max filter works.n
Example 1: Finding the Maximum Number 📈
nThis is the most common use case. You have a list of numbers and you want to find the highest value.nnJinja Template:n
{% set temperatures = [22, 18, 25, 15, 20] %}n<p>The highest temperature recorded was: {{ temperatures | max }}°C</p>
nRendered HTML:n
<p>The highest temperature recorded was: 25°C</p>
nn
nn
Example 2: Finding the Maximum String (Case-Insensitive)
nBy default, string comparisons are case-insensitive.nnJinja Template:n
{% set names = ['Charlie', 'alice', 'Bob'] %}n<p>The name that comes last alphabetically is: {{ names | max }}</p>
nRendered HTML:n
<p>The name that comes last alphabetically is: Charlie</p>
nSince the comparison is case-insensitive, Charlie comes after alice and Bob alphabetically.nn
nn
Example 3: Finding the Object with the Maximum Attribute Value 💰
nThis is where the attribute parameter is useful. You can find the entire object that has the highest value for a specific key.nnPython Code:n
# 'products' is passed to the templatenproducts = [n {'name': 'Laptop', 'price': 1200.00},n {'name': 'Mouse', 'price': 25.00},n {'name': 'Keyboard', 'price': 75.00}n]
nJinja Template:n
{% set most_expensive_product = products | max(attribute='price') %}n<h3>Most Expensive Product: {{ most_expensive_product.name }}</h3>n<p>Price: ${{ most_expensive_product.price }}</p>
nRendered HTML:n
<h3>Most Expensive Product: Laptop</h3>n<p>Price: $1200.00</p>
nThe filter looks at the price attribute for each object and returns the entire object for the one with the highest value.nn
