0
0
Flaskframework~5 mins

Control structures (if, for) in Flask

Choose your learning style9 modes available
Introduction

Control structures help decide what to show or repeat in your web page. They let your page change based on data or conditions.

Show a message only if a user is logged in.
List all items in a shopping cart.
Display a special offer only on weekends.
Repeat a block of HTML for each product in a catalog.
Syntax
Flask
{% if condition %}
  <!-- HTML to show if true -->
{% elif other_condition %}
  <!-- HTML to show if other condition true -->
{% else %}
  <!-- HTML to show if none true -->
{% endif %}

{% for item in list %}
  <!-- HTML repeated for each item -->
{% endfor %}
Use {% %} to write control structures in Flask templates (Jinja2).
Indent HTML inside control blocks for clarity.
Examples
Shows a welcome message if the user is logged in, otherwise asks to log in.
Flask
{% if user.is_logged_in %}
  <p>Welcome back!</p>
{% else %}
  <p>Please log in.</p>
{% endif %}
Lists each product's name and price inside a list item.
Flask
{% for product in products %}
  <li>{{ product.name }} - ${{ product.price }}</li>
{% endfor %}
Shows a sale message only on weekends.
Flask
{% if day == 'Saturday' or day == 'Sunday' %}
  <p>Enjoy the weekend sale!</p>
{% endif %}
Sample Program

This template greets the user by name. If the user is logged in, it shows how many items are in their cart and lists each product with its price. If not logged in, it asks the user to log in.

Flask
{% set user = {'name': 'Anna', 'is_logged_in': True} %}
{% set products = [
  {'name': 'Book', 'price': 12.99},
  {'name': 'Pen', 'price': 1.50}
] %}

<h1>Hello, {{ user.name }}!</h1>

{% if user.is_logged_in %}
  <p>You have {{ products|length }} items in your cart:</p>
  <ul>
  {% for product in products %}
    <li>{{ product.name }} - ${{ product.price }}</li>
  {% endfor %}
  </ul>
{% else %}
  <p>Please log in to see your cart.</p>
{% endif %}
OutputSuccess
Important Notes

Remember to close your control blocks with {% endif %} and {% endfor %}.

You can use filters like |length to get the number of items in a list.

Control structures only work inside Flask templates, not in Python code files.

Summary

Use {% if %} to show HTML only when a condition is true.

Use {% for %} to repeat HTML for each item in a list.

Control structures make your web pages dynamic and responsive to data.