0
0
FlaskHow-ToBeginner · 3 min read

How to Use If Else in Jinja2 Templates with Flask

In Flask, you use {% if condition %} ... {% else %} ... {% endif %} in Jinja2 templates to run conditional logic. This lets you show different content depending on values passed from your Flask app.
📐

Syntax

The if else statement in Jinja2 uses tags to control what HTML is shown based on a condition.

  • {% if condition %}: Starts the condition block.
  • {% else %}: Defines the alternative block if the condition is false.
  • {% endif %}: Ends the conditional block.
jinja2
{% if user.is_authenticated %}
  <p>Welcome, {{ user.name }}!</p>
{% else %}
  <p>Please log in.</p>
{% endif %}
💻

Example

This example shows a simple Flask app passing a user object to a Jinja2 template. The template uses if else to greet logged-in users or ask visitors to log in.

python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    user = {'is_authenticated': True, 'name': 'Alice'}
    return render_template('home.html', user=user)

# Template: templates/home.html
#
# {% if user.is_authenticated %}
#   <h1>Welcome, {{ user.name }}!</h1>
# {% else %}
#   <h1>Please log in.</h1>
# {% endif %}

if __name__ == '__main__':
    app.run(debug=True)
Output
<h1>Welcome, Alice!</h1>
⚠️

Common Pitfalls

Common mistakes include forgetting the closing {% endif %} tag, using Python-style if: syntax instead of Jinja2 tags, or mixing variable syntax inside the condition.

Always use Jinja2 tags {% %} for control flow, and {{ }} only for outputting values.

jinja2
{# Wrong: missing endif #}
{% if user.is_authenticated %}
  <p>Welcome!</p>

{# Correct: includes endif #}
{% if user.is_authenticated %}
  <p>Welcome!</p>
{% endif %}
📊

Quick Reference

TagPurpose
{% if condition %}Start a conditional block
{% elif condition %}Add another condition (optional)
{% else %}Fallback if all conditions fail
{% endif %}End the conditional block

Key Takeaways

Use {% if %} ... {% else %} ... {% endif %} tags in Jinja2 templates for conditional rendering.
Pass variables from Flask to templates to control conditions dynamically.
Always close your if blocks with {% endif %} to avoid template errors.
Use {% elif %} for multiple conditions if needed.
Remember to use Jinja2 syntax, not Python syntax, inside templates.