BudiBadu Logo
Samplebadu

Flask by Example: Template Conditional Blocks

Flask 3.0+

Conditional logic allows your templates to adapt based on the data. You can show or hide elements, apply different classes, or render entirely different layouts using `if`, `elif`, and `else`.

Code

<!-- templates/dashboard.html -->
<div class="user-panel">
    <!-- 1. Basic check -->
    {% if user %}
        <p>Hello, {{ user.username }}</p>
        
        <!-- 2. Complex logic with operators -->
        {% if user.is_active and user.role == 'admin' %}
            <button class="btn-admin">Admin Settings</button>
            
        {% elif user.role == 'moderator' %}
            <button class="btn-mod">Mod Tools</button>
            
        {% else %}
            <p>Standard User Account</p>
        {% endif %}
        
    {% else %}
        <a href="/login">Log In</a>
    {% endif %}
</div>

<!-- 3. Inline if (Ternary operator equivalent) -->
<div class="status {{ 'active' if is_online else 'offline' }}">
    Status: {{ 'Online' if is_online else 'Offline' }}
</div>

<!-- 4. Checking for existence/definition -->
{% if sidebar_content is defined %}
    <aside>{{ sidebar_content }}</aside>
{% endif %}

Explanation

The {% if %} tag controls the flow of your template using standard Python comparison and logical operators. It allows you to conditionally display content based on the data passed to the template.

Jinja2 also supports inline if expressions, which are perfect for concise conditional output. This is commonly used for toggling CSS classes or displaying simple status messages without the verbosity of a full block.

You can also check if a variable exists using the is defined test. This allows for flexible templates that can handle optional context variables gracefully, preventing errors when data is missing.

Code Breakdown

7
and operator works just like Python. You can chain multiple conditions. Parentheses can be used for grouping if needed.
10
{% elif %} allows for multiple branches. The block ends with a single {% endif %}.
21
Inline if syntax: {{ value_if_true if condition else value_if_false }}. This is cleaner than a full block for simple string outputs.
26
is defined is a Jinja test. It returns true if the variable exists in the context. This prevents "undefined variable" errors.