While our Flask app works, it is not very attractive or informative. Let’s make it more appealing and personalized by creating a template and a route for the welcome message. A template is a file that contains HTML code with placeholders for dynamic content. A route is a function that handles a request for a specific URL and returns a response. We can use templates and routes to render different pages for our app.
To create a template, we need to use the Jinja2 template engine that Flask integrates with. Jinja2 is a powerful and flexible template engine that allows us to write HTML code with Python expressions and control structures. To use Jinja2, we need to create a directory called templates in the current working directory and store our template files there. Flask will automatically look for templates in this directory.
Let’s create a file called index.html in the templates directory and write the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask App</title>
</head>
<body>
<h1>Welcome to my Flask app!</h1>
<p>This is a simple Flask app that displays a welcome message.</p>
<p>The welcome message is: {{ message }}</p>
</body>
</html>
This code does the following:
Defines the HTML document structure and the metadata
Displays a heading and two paragraphs of text
Uses a placeholder message to insert a dynamic value that we will pass from our route
To create a route, we need to use the app.route decorator and the render_template function that Flask provides. The app.route decorator maps a URL to a function that handles the request and returns the response. The render_template function renders a template with the given context variables and returns the result as a string.
Let’s modify our app.py file and write the following code:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
message = "Hello, world!"
return render_template("index.html", message=message)
This code does the following:
- Imports the render_template function from the flask module
- Defines a route for the root URL (“/”) using the app.route decorator
- Defines a function called index that assigns a string “Hello, world!” to the message variable and passes it to the render_template function along with the name of the template file
To see the result of our changes, we need to restart the Flask development server by pressing Ctrl+C in the terminal and running the following command again:
flask run
This will restart the server and display the URL where we can access our app. If we open this URL in a web browser, we should see our new welcome page:
As you can see, our Flask app now displays a more attractive and personalized welcome message. 🙌
Top comments (0)