What is the if Expression?
n
if expression is a concise, single-line conditional that returns a value based on a condition. Unlike the multi-line {% if ... %} statement which controls the rendering of a block of content, the if expression is used to assign or display a value. It’s a powerful tool for cleaning up your templates by replacing verbose if statements with a single line of code, especially for simple conditional logic.nn
nn
Syntax and Usage
nThe if expression follows a simple and readable structure, similar to a ternary operator in many programming languages. It must have both an if and an else clause.n
Basic Syntax
n
{{ value_if_true if condition else value_if_false }}
n
- n
condition: The expression that is evaluated to beTrueorFalse.value_if_true: The value returned if the condition isTrue.value_if_false: The value returned if the condition isFalse.
n
n
n
n
Example
nLet’s say you want to display “Active” or “Inactive” next to a user’s name.n
<p>User Status: {{ 'Active' if user.is_active else 'Inactive' }}</p>
nIf user.is_active is True, the output will be <p>User Status: Active</p>. Otherwise, it will be <p>User Status: Inactive</p>.n
Using the if Expression to Set a Variable
nYou can also use the if expression within the {% set ... %} tag to conditionally assign a value to a variable.n
{% set status_class = 'bg-green' if user.is_active else 'bg-red' %}n<p class="{{ status_class }}">Status</p>
nThis is a clean way to dynamically set CSS classes or other attributes without a multi-line if statement.nn
nn
Comparison with the if Statement
nIt’s important to understand the difference between the if expression and the if statement.n
- n
ifStatement ({% if ... %}): Controls the flow of a block of content. It can includeelifandelseclauses and is used for rendering entire sections of a template.ifExpression (... if ... else ...): Returns a single value. It’s used within an output tag{{ ... }}or asettag to provide a value for a variable.
n
n
nThe if expression is a tool for data assignment, while the if statement is a tool for control flow.nn
nn
Full Demonstration
nHere is a complete example of a Jinja2 template and the Python code to render it, demonstrating different ways to use the if expression.n
Jinja2 Template (products.html)
n
<!DOCTYPE html>n<html lang="en">n<head>n <meta charset="UTF-8">n <title>Product List</title>n <style>n .in-stock { color: green; }n .out-of-stock { color: red; }n .price-normal { font-weight: normal; }n .price-bold { font-weight: bold; }n </style>n</head>n<body>nn <h1>Product Inventory</h1>n n {% for product in products %}n n {% set stock_status = 'In Stock' if product.in_stock else 'Out of Stock' %}n {% set price_style = 'price-bold' if product.price > 50 else 'price-normal' %}nn <div style="border: 1px solid #ccc; padding: 10px; margin-bottom: 10px;">n <h3>{{ product.name }}</h3>n <p><strong>Price:</strong> <span class="{{ price_style }}">${{ product.price }}</span></p>n <p>n <strong>Status:</strong> n <span class="{{ 'in-stock' if product.in_stock else 'out-of-stock' }}">n {{ stock_status }}n </span>n </p>n <p>Available: {{ product.stock_count if product.in_stock else 0 }}</p>n </div>n n {% endfor %}nn</body>n</html>
n
Python Code to Render the Template
n
from jinja2 import Environment, FileSystemLoader
ndata = {n’products’: [n{‘name’: ‘Laptop’, ‘price’: 1200, ‘in_stock’: True, ‘stock_count’: 5},n{‘name’: ‘Mouse’, ‘price’: 25, ‘in_stock’: True, ‘stock_count’: 15},n{‘name’: ‘Keyboard’, ‘price’: 75, ‘in_stock’: False, ‘stock_countn
n
n
