In this lesson, you'll dive into the fundamentals of building web applications with Flask. You'll learn how to create dynamic web pages using Flask templates (with Jinja2) and how to manage navigation using Flask's routing capabilities. By the end, you'll have a basic multi-page web app.
Flask templates are used to separate your HTML code from your Python code. This makes your application more organized and easier to maintain. Flask uses the Jinja2 templating engine, which allows you to embed Python code within your HTML files. This lets you dynamically generate content based on data from your Python code.
To create a template, you'll typically store your HTML files in a folder named templates
in the same directory as your Flask app.
Example: Let's create a simple HTML file named index.html
:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>My First Flask App</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>Welcome to my Flask application.</p>
</body>
</html>
In this example, {{ name }}
is a placeholder for a variable. We'll pass the value of name
from our Python code.
To render a template, you use the render_template()
function from the flask
library. This function takes the template filename as an argument, and you can pass data to the template as keyword arguments.
Example: Let's update our app.py
file:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
name = "User"
return render_template("index.html", name=name)
if __name__ == "__main__":
app.run(debug=True)
In this code:
render_template
.@app.route("/")
decorator defines the root URL (/
) for the index page.index()
function renders the index.html
template, passing the name
variable to it.http://127.0.0.1:5000/
(or whatever address your terminal provides). You should see "Hello, User!" in your browser.Flask uses decorators to define routes. A route is a URL path that, when accessed, triggers a specific function in your Flask application. The @app.route()
decorator associates a function with a URL.
Example: Let's add a second page to our app.
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
name = "User"
return render_template("index.html", name=name)
@app.route("/about")
def about():
return render_template("about.html")
if __name__ == "__main__":
app.run(debug=True)
Now, we need an about.html
template (create a file templates/about.html
):
<!-- templates/about.html -->
<!DOCTYPE html>
<html>
<head>
<title>About Us</title>
</head>
<body>
<h1>About Us</h1>
<p>This is the about page.</p>
</body>
</html>
Now, when you visit http://127.0.0.1:5000/about
, you'll see the content of the about.html
page. The @app.route("/about")
decorator maps this URL to the about()
function.
To make our application navigable, we can add links within our HTML templates. In HTML, use the <a href="/your_route">link text</a>
tag to create links. For example, in index.html
and about.html
, let's add navigation links.
Example: Modify index.html
:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>My First Flask App</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>Welcome to my Flask application.</p>
<a href="/about">About</a>
</body>
</html>
And modify about.html
:
<!-- templates/about.html -->
<!DOCTYPE html>
<html>
<head>
<title>About Us</title>
</head>
<body>
<h1>About Us</h1>
<p>This is the about page.</p>
<a href="/">Home</a>
</body>
</html>
Now your app should be navigable between the index page and the about page.
Explore advanced insights, examples, and bonus exercises to deepen understanding.
Now that you've built a basic multi-page Flask application using templates and routing, let's explore ways to make your web application more dynamic, efficient, and interactive. We'll delve into advanced template features, error handling, and the potential for integrating with external APIs. This lays the groundwork for understanding how to eventually integrate with Android system notifications, which we'll touch upon later in the learning journey.
Jinja2 is more powerful than simply displaying static and dynamic text. Let's look at some advanced features:
Consider the following example for template inheritance:
{# base.html - Base template #}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My App{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<main>
{% block content %}{% endblock %}
</main>
<footer>
<p>© 2023</p>
</footer>
</body>
</html>
{# index.html - Child template #}
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h2>Welcome!</h2>
<p>This is the homepage.</p>
{% endblock %}
Here are some exercises to further solidify your understanding:
These concepts are incredibly valuable in real-world web development:
For a more challenging exercise, consider the following:
To expand your knowledge further, explore these topics:
Create a new route and template for a 'Contact' page. The route should be `/contact`, and the template should display a simple form (you don't need to make it functional). Include a navigation link from the other pages to the contact page. The `contact.html` file should be located in the templates folder.
Modify the `index()` function to accept a name as a URL parameter (e.g., `/hello/<name>`). Update the `index.html` template to greet the provided name. For example, if someone visits `/hello/Alice`, the page should say 'Hello, Alice!'
Think about how you could create a base template (a layout) that contains common elements like headers, footers, and navigation. How would this simplify creating multiple pages? Sketch out an example of a base template and how child templates might inherit from it. (Don't implement it yet, just brainstorm).
Build a simple website for a fictional business. Include a home page, an about page, and a contact page, all using templates and routing. Add a menu to navigate between pages.
Prepare for the next lesson by reviewing the basics of HTML and CSS, especially focusing on the structure of HTML and basic styling elements. We will explore how to apply CSS and static resources in flask next.
We're automatically tracking your progress. Sign up for free to keep your learning paths forever and unlock advanced features like detailed analytics and personalized recommendations.