Jinja2 Logic Operator: The expr Concept
n
expr is not a specific keyword or operator in Jinja2, like if, or, or not. Instead, “expr” is a syntactic term that stands for “expression.” It refers to any piece of code that returns a value. In Jinja2’s context, an expression is what you place inside the {% ... %} control tags or {{ ... }} output tags. When you use an if statement, Jinja2 evaluates the expression provided to determine if it is “truthy” or “falsy.”nn
nn
How Expression Evaluation Works
nJinja2, like Python, uses a concept of truthiness. This means that certain values are implicitly treated as True or False in a conditional context, even if they aren’t the boolean values True or False themselves.n
- n
- Falsy values (evaluated as
False):n- n
FalseNone0(the integer zero)0.0(the float zero)- An empty string (
'') - An empty list (
[]) or tuple (()) - An empty dictionary (
{})
n
n
n
n
n
n
n
n
- Truthy values (evaluated as
True):n- n
True- Any number other than
0 - Any non-empty string
- Any non-empty list, tuple, or dictionary
n
n
n
n
n
n
n
nWhen you write {% if my_variable %}, Jinja2 checks the value of my_variable to see if it is truthy. This fundamental concept allows for very concise and readable conditional logic.nn
nn
Code Samples Demonstrating expr
n
1. Basic Truthiness Check
nThis example shows how an if statement evaluates a variable’s truthiness to control content rendering.nnJinja2 Templaten
{% if user_name %}n <p>Welcome, {{ user_name }}!</p>n{% else %}n <p>Welcome, guest.</p>n{% endif %}nn{% set items = ['apple', 'banana'] %}n{% if items %}n <p>You have items in your cart.</p>n{% endif %}
nExplanation: In the first block, if user_name is a non-empty string, it’s considered True, and the welcome message is rendered. If it’s an empty string or None, it’s False, and the “guest” message is shown. In the second block, the items list, because it’s not empty, is truthy, so the message is displayed.nn
nn
2. Using expr in if Expressions
nThe expr concept is also key to the single-line if expression, allowing you to return a value based on a condition.nnJinja2 Templaten
<p>You have {{ cart_items|length if cart_items else 0 }} items.</p>
nExplanation: Here, the expression cart_items is evaluated. If the list is not empty (truthy), the length filter is applied. If the list is empty (falsy), the value 0 is used.nn
nn
Full Demonstration
nThis example combines multiple concepts to show the power of expression evaluation in a real-world scenario.n
Jinja2 Template (report.html)
n
<!DOCTYPE html>n<html lang="en">n<head>n <title>Dashboard Report</title>n</head>n<body>n <h1>User Profile</h1>n {% set is_active = user.status == 'active' %}n <p>Status: {{ 'Online' if is_active else 'Offline' }}</p>nn <h1>Notifications</h1>n {% if notifications %}n <p>You have {{ notifications|length }} new messages!</p>n {% else %}n <p>You have no new messages.</p>n {% endif %}nn <h1>Payment Status</h1>n {% set payment_due = user.balance > 0 %}n {% if payment_due %}n <p>Your account has a balance of ${{ user.balance }}. Please pay now.</p>n {% endif %}nn</body>n</html>
n
Python Code to Render the Template
n
from jinja2 import Environment, FileSystemLoadernn# Sample Data 1: User with notifications and a balancendata1 = {n 'user': {n 'status': 'active',n 'balance': 50.00n },n 'notifications': ['message1', 'message2']n}nn# Sample Data 2: Inactive user with no notificationsndata2 = {n 'user': {n 'status': 'inactive',n 'balance': 0.00n },n 'notifications': []n}nnenv = Environment(loader=FileSystemLoader('.'))ntemplate = env.get_template('report.html')nnprint("--- Data Set 1 Output ---")nrendered_html1 = template.render(data1)nprint(rendered_html1)nnprint("\n\n--- Data Set 2 Output ---")nrendered_html2 = template.render(data2)nprint(rendered_html2)
n
Rendered HTML Output
n— Data Set 1 Output —n
<!DOCTYPE html>n<html lang="en">n<head>n <title>Dashboard Report</title>n</head>n<body>n <h1>User Profile</h1>n <p>Status: Online</p>nn <h1>Notifications</h1>n <p>You have 2 new messages!</p>nn <h1>Payment Status</h1>n <p>Your account has a balance of $50.0. Please pay now.</p>nn</body>n</html>
n— Data Set 2 Output —n
<!DOCTYPE html>n<html lang="en">n<head>n <title>Dashboard Report</title>n</head>n<body>n <h1>User Profile</h1>n <p>Status: Offline</p>nn <h1>Notifications</h1>n <p>You have no new messages.</p>nn <h1>Payment Status</h1>nn</body>n</html>
n
n
