Jinja2’s if statement is a fundamental control structure that allows you to render content conditionally. It works just like an if statement in a programming language, executing a block of code only if a given condition is True. This is essential for creating dynamic templates that adapt to different data and user states.n
nn
Basic if Statement
nThe simplest form of the if statement checks a single condition. If the condition evaluates to True, the code block inside the statement is rendered. The block is defined by the {% if ... %} and {% endif %} tags.n
Syntax
n
{% if user.is_active %}n <p>Welcome back, {{ user.name }}!</p>n{% endif %}
nIn this example, the paragraph will only be included in the final output if the user.is_active variable is True. If it is False or undefined, the entire block is skipped.nn
nn
Using else
nYou can provide an alternative block of code to be executed when the if condition is False using the else clause. This ensures that some content is always rendered, regardless of the outcome of the condition.n
Syntax
n
{% if user.is_logged_in %}n <a href="/logout">Logout</a>n{% else %}n <a href="/login">Login</a>n{% endif %}
nHere, if the user is logged in, the “Logout” link is shown. If not, the “Login” link is shown instead.nn
nn
Handling Multiple Conditions with elif
nFor situations with more than two possible outcomes, you can use the elif (short for “else if”) clause. This allows you to check a series of conditions sequentially. The first if or elif condition that evaluates to True will have its block rendered, and all subsequent elif and else blocks will be skipped.n
Syntax
n
{% if user.role == 'admin' %}n <p>Hello, Admin!</p>n{% elif user.role == 'moderator' %}n <p>Hello, Moderator!</p>n{% else %}n <p>Hello, User!</p>n{% endif %}
nThis example checks the user.role variable. If it’s 'admin', the first block runs. If not, it checks if it’s 'moderator'. If neither of those conditions are met, the final else block is executed.nn
nn
Common Usage and Examples
nYou can use a wide range of logical expressions and operators within Jinja’s if statements.n
Checking a Boolean or Variable
nA variable’s existence is a common check. The defined test is particularly useful.n
{% if show_promo %}n <div class="promo">Limited-time offer!</div>n{% endif %}nn{% if user is defined %}n <p>Welcome, {{ user.name }}!</p>n{% else %}n <p>Welcome, guest!</p>n{% endif %}
n
Comparing Values
nYou can compare numbers and strings using standard operators (==, !=, >).n
{% if product.stock > 0 %}n <p>In Stock</p>n{% else %}n <p>Out of Stock</p>n{% endif %}
n
Logical Operators (and, or, not)
nCombine multiple conditions for more complex logic.n
{% if user.is_active and user.has_subscription %}n <p>Access Granted</p>n{% elif user.is_active or user.is_trial %}n <p>Trial Access</p>n{% else %}n <p>Access Denied</p>n{% endif %}
nn
nn
Full Demonstration
nHere is a complete example that shows a Jinja2 template, the Python code used to render it, and the resulting HTML.n
Jinja2 Template (report.html)
n
<!DOCTYPE html>n<html lang="en">n<head>n <title>User Report</title>n</head>n<body>nn {% if users|length > 0 %}n <h1>Active Users</h1>n <hr>n {% for user in users %}n <div class="user-card">n <h3>{{ user.name }}</h3>n {% if user.is_admin %}n <p>Role: Administrator</p>n {% elif user.is_moderator %}n <p>Role: Moderator</p>n {% else %}n <p>Role: Standard User</p>n {% endif %}nn {% if loop.index is odd %}n <p>This is an odd-numbered user.</p>n {% endif %}n </div>n {% endfor %}n {% else %}n <p>No users found.</p>n {% endif %}nn</body>n</html>
n
Python Code to Render the Template
n
from jinja2 import Environment, FileSystemLoadernn# Sample datandata = {n 'users': [n {'name': 'Alice', 'is_admin': True, 'is_moderator': False},n {'name': 'Bob', 'is_admin': False, 'is_moderator': False},n {'name': 'Charlie', 'is_admin': False, 'is_moderator': True},n ]n}nn# Create a Jinja2 environment and load the templatenenv = Environment(loader=FileSystemLoader('.'))ntemplate = env.get_template('report.html')nn# Render the template with the datanrendered_html = template.render(data)nprint(rendered_html)
n
Rendered HTML Output
n
<!DOCTYPE html>n<html lang="en">n<head>n <title>User Report</title>n</head>n<body>nn <h1>Active Users</h1>n <hr>n n <div class="user-card">n <h3>Alice</h3>n n <p>Role: Administrator</p>n n n <p>This is an odd-numbered user.</p>n n </div>n n <div class="user-card">n <h3>Bob</h3>n n <p>Role: Standard User</p>n n n </div>n n <div class="user-card">n <h3>Charlie</h3>n n <p>Role: Moderator</p>n n n <p>This is an odd-numbered user.</p>n n </div>n nn</body>n</html>
n
n
