Flask Tutorials: Template Control Structures (if, for)

beginner
25 min

Flask Tutorials: Template Control Structures (if, for)

Welcome to the second part of our Flask tutorials! Today, we'll dive into the world of template control structures, focusing on the if and for statements. These are essential tools for creating dynamic, user-friendly web applications with Flask.

Before we get started, make sure you've gone through our previous lesson on Flask basics. If not, take a quick detour there before diving in!

📝 Note:

The control structures we'll discuss today are used in Jinja2 templates, Flask's templating engine.

Understanding the if statement

Just like in many programming languages, the if statement in Flask checks a condition and executes code if the condition is true.

Simple if Statement

Let's create a simple example where we check if a user is logged in or not.

python
# app.py from flask import Flask, render_template from flask_login import LoginManager, UserMixin, current_user app = Flask(__name__) login_manager = LoginManager() class User(UserMixin): # User details @app.route('/') def home(): if current_user.is_authenticated: return render_template('home_logged_in.html') else: return render_template('home_logged_out.html') # Configure Flask-Login # ... if __name__ == '__main__': app.run()

In this example, we're using the current_user object from flask_login to check if a user is logged in. Depending on the result, we render different templates.

Nested if Statements

Nested if statements allow you to check multiple conditions. Here's an example where we check the day of the week and greet the user accordingly.

python
def get_greeting(): day = datetime.datetime.now().weekday() if 0 <= day < 5: return "Good day!" else: return "Good evening!" @app.route('/') def home(): greeting = get_greeting() if current_user.is_authenticated: greeting += ", welcome back!" return render_template('home.html', greeting=greeting)

In this example, we use a helper function get_greeting() to determine the current day. Depending on the result, we append a different message to the greeting before rendering the template.

🎯 Embracing the for Loop

The for loop in Flask is used to iterate over a sequence, such as a list or dictionary, and execute code for each item in the sequence.

Basic for Loop

Here's an example where we display a list of users on the homepage.

python
@app.route('/') def home(): users = [User(name='Alice', email='alice@example.com'), User(name='Bob', email='bob@example.com'), User(name='Charlie', email='charlie@example.com')] return render_template('home.html', users=users)

In this example, we create a list of users and pass it to our template. We'll use the for loop in the template to iterate over the users and display each user's details.

Nested for Loops

Nested for loops allow you to iterate over multiple sequences simultaneously. Here's an example where we display a table of users and their associated posts.

python
posts = [ {'user_id': 1, 'title': 'Post 1', 'content': 'Content 1'}, {'user_id': 2, 'title': 'Post 2', 'content': 'Content 2'}, {'user_id': 3, 'title': 'Post 3', 'content': 'Content 3'}, ] @app.route('/') def home(): users = [User(name='Alice', email='alice@example.com'), User(name='Bob', email='bob@example.com'), User(name='Charlie', email='charlie@example.com')] return render_template('home.html', users=users, posts=posts)

In this example, we create a list of posts and pass it to our template. We'll use nested for loops in the template to iterate over the users and their associated posts, creating a table of user posts.

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `if` statement in Flask?

Quick Quiz
Question 1 of 1

What is the purpose of the `for` loop in Flask?