Jinja Arithmetic Expression: -
n
- operator in Jinja2 is an arithmetic operator that subtracts the second number from the first one. It is a fundamental tool for performing calculations within a template, such as determining a remaining balance, calculating a difference, or displaying a negative value. Its behavior is consistent with the `-` operator in Python. ➖nn
nn
How It Works
nThe `-` operator is exclusively used for performing subtraction on numerical values (integers and floats). When Jinja2 encounters the expression number1 - number2, it performs the mathematical operation and returns the result. You can use the result directly in your template or store it in a variable for later use.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. Subtracting Numerical Values
nThis is the most common use case, often used to calculate a remaining balance or a difference.nnJinja2 Templaten
{% set total_amount = 100 %}n{% set amount_paid = 75 %}n<p>Remaining balance: ${{ total_amount - amount_paid }}</p>
nExplanation: The template subtracts `amount_paid` from `total_amount`, resulting in the output “Remaining balance: $25”.nn
nn
2. Using - with a for Loop
nYou can use the operator to perform calculations on each item within a loop, for example, calculating the number of items remaining after a purchase.nnJinja2 Templaten
{% set products = [{ 'name': 'Laptop', 'stock': 20 }, { 'name': 'Mouse', 'stock': 15 }] %}n<ul>n{% for product in products %}n <li>{{ product.name }}: {{ product.stock - 5 }} remaining after a purchase of 5.</li>n{% endfor %}n</ul>
nExplanation: This loop iterates through a list of products. For each product, it subtracts `5` from its `stock` value and displays the result. The output will be a list showing the remaining stock for each item.nn
nn
3. Working with Negative Numbers
nThe `-` operator handles negative numbers correctly, allowing you to perform calculations that result in a negative value or use a negative number in an operation.nnJinja2 Templaten
{% set temperature = 5 %}n{% set temperature_change = -10 %}n<p>Final temperature: {{ temperature + temperature_change }} degrees Celsius.</p>
nExplanation: While this example uses addition, the `temperature_change` variable is negative, and the operation effectively becomes a subtraction, resulting in a final temperature of -5 degrees Celsius.nn
n
