Jinja Comparison Expression: <
n
< operator in Jinja2 is a comparison operator that returns true if the value on the left side is strictly less than the value on the right side. It is a fundamental tool for controlling template logic based on numerical or alphabetical order. This behavior is consistent with how the < operator works in Python.nn
nn
How It Works
nThe < operator is typically used within an if statement to evaluate a condition. Jinja2’s templating engine evaluates the expression variable1 < variable2. If the expression is true, the content within the if block is rendered. This is perfect for displaying content only when a value falls below a certain threshold, such as showing a “Low Stock” warning for products or a “Try Again” message for a low score.n
Syntax
n
{% if value1 < value2 %}n ... content to display if the condition is true ...n{% endif %}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use the < operator in a Jinja2 application.n
1. Comparing Numerical Values
nThis is the most common use case for the < operator, often used to check against a threshold.nnJinja2 Templaten
{% set user_score = 75 %}n{% if user_score < 100 %}n <p>You're almost there! Keep practicing to get a high score.</p>n{% else %}n <p>You've achieved a high score!</p>n{% endif %}
nExplanation: The template checks if the numerical value of user_score is less than 100. Since 75 is less than 100, the motivational message is rendered.nn
nn
2. Using < with for Loops
nYou can use the < operator inside a loop to conditionally filter items based on a numerical or alphabetical condition.nnJinja2 Templaten
{% set products = [{ 'name': 'Laptop', 'price': 1500 }, { 'name': 'Mouse', 'price': 50 }, { 'name': 'Keyboard', 'price': 120 }] %}n<h4>Budget Products (< $100):</h4>n<ul>n{% for product in products %}n {% if product.price < 100 %}n <li>{{ product.name }} (${{ product.price }})</li>n {% endif %}n{% endfor %}n</ul>
nExplanation: This loop iterates through a list of products. The if statement checks if the price attribute of each product is less than 100. Only products that meet this condition are rendered in the list.nn
nn
3. Comparing Strings Alphabetically
nThe < operator can also be used to compare strings based on their alphabetical order.nnJinja2 Templaten
{% set current_word = 'apple' %}n{% if current_word < 'banana' %}n <p>The word 'apple' comes before 'banana' alphabetically.</p>n{% else %}n <p>The word 'apple' does not come before 'banana' alphabetically.</p>n{% endif %}
nExplanation: The template checks the alphabetical order of the strings. In this case, `’apple’` is alphabetically less than `’banana’`, so the `if` block is rendered.nn
n
