Rendering HTML with Flask Templates

Rendering HTML with Flask Templates

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.

Setting Up the Project Structure

Before we begin, let’s briefly revisit the project structure we have so far. Your Flask project directory should look something like this:

app/

├── app.py
└── 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.

Creating the HTML Template

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:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to your Flask App!</h1>
</body>
</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.

Rendering a Template in Flask

In app/app.py, let's update our route and make sure to import the necessary function:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def welcome():
    # Render the 'welcome.html' template from the 'templates' directory
    return render_template('welcome.html')

if __name__ == '__main__':
    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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal