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!
The control structures we'll discuss today are used in Jinja2 templates, Flask's templating engine.
if statementJust like in many programming languages, the if statement in Flask checks a condition and executes code if the condition is true.
if StatementLet's create a simple example where we check if a user is logged in or not.
# 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.
if StatementsNested 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.
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.
for LoopThe 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.
for LoopHere's an example where we display a list of users on the homepage.
@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.
for LoopsNested 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.
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.
What is the purpose of the `if` statement in Flask?
What is the purpose of the `for` loop in Flask?