Welcome back! Previously, you learned how to set up a basic Flask application and create a simple route that returns a string. In this lesson, we will dive into rendering HTML templates with Flask.
In the context of the Model-View-Controller (MVC) pattern, a template corresponds to the View. It is essentially a file, often in HTML, that defines the structure and layout of your web pages. Templates allow us to separate the presentation layer from the business logic, making it easier to manage and maintain our web application.
Before we begin, let’s briefly revisit the project structure we have so far. Your Flask project directory should look something like this:
Plain text1app/ 2│ 3├── app.py 4└── templates/
app/
: This is our main project directory.app.py
: This file will contain our main Flask application code.templates/
: This directory will contain all of our HTML templates.
Make sure to create a templates
directory within your app
directory to store all your HTML files. The templates
directory is essential for rendering HTML templates in Flask because Flask automatically looks for HTML files in this directory when using the render_template
function.
Let’s create an HTML template that our Flask app will render. Inside the templates
directory, we’ll create a new file named welcome.html
with the following content:
HTML, XML1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Welcome</title> 7</head> 8<body> 9 <h1>Welcome to your Flask App!</h1> 10</body> 11</html>
This HTML template provides a basic structure with a title and a welcome message. Now, let's integrate this template into our Flask application.
In app/app.py
, let's update our route and make sure to import the necessary function:
Python1from flask import Flask, render_template 2 3app = Flask(__name__) 4 5@app.route('/') 6def welcome(): 7 # Render the 'welcome.html' template from the 'templates' directory 8 return render_template('welcome.html') 9 10if __name__ == '__main__': 11 app.run(host='0.0.0.0', port=3000, debug=True)
Here, we’re importing the render_template
function from Flask. In our welcome
function, we use it to load the welcome.html
file from the templates
directory. When someone accesses the root URL, Flask will render the HTML template and display it to the client.
And that’s it! We have successfully created and rendered an HTML template with Flask.
In this lesson, you’ve learned:
- What templates are and why they are useful in web development.
- How to create and structure an HTML file for using as a template.
- How to modify a Flask application to render an HTML template.
With a solid grasp of rendering HTML using Flask, you can now proceed to the practice exercises. These activities will help consolidate your understanding and boost your confidence in using Flask templates. Feel free to modify the template and delve into other features Flask offers.