Jinja Inline if and Loop Filtering
n
The Jinja2 templating engine offers two powerful ways to handle conditional logic compactly: the **inline if statement** and **loop filtering**. Both methods make your templates cleaner and easier to read by avoiding multi-line if blocks.
nn
Inline if Statement
n
This acts as a ternary operator, providing a concise way to choose between two values based on a single condition. It’s great for displaying a simple message or assigning a variable.
nn
{# Display a user's status directly #}
nThe user’s status is: {{ ‘Logged In’ if user.authenticated else ‘Guest’ }}n
n{# Set a variable based on a condition #} {% set stock_status = ‘In Stock’ if product.in_stock else ‘Out of Stock’ %}n
nThis product is {{ stock_status }}.n
n n
n
nn
Filtering with if in Loops
n
You can use an if condition directly within a `for` loop to iterate over only the items that meet a specific requirement. This is an elegant way to filter data without writing a separate if block inside your loop.
nn
{# Only loop over featured products #}
n
Featured Products
n
n n
n
- n
- n
- {% for product in products if product.featured %}n
- {{ product.name }}
n
n
n
n{% endfor %}n
n{# Only display items with a count greater than zero #}n
n
Available Items
n
n n
n
- n
- n
- {% for item in inventory if item.count > 0 %}n
- {{ item.name }} ({{ item.count }} left)
n
n
n
n{% endfor %}n
n
n
