HTML templates in Flask (Jinja2)
In the previous lesson we learned how Flask uses routes (URL paths) to link web addresses with Python functions.
Now we will learn how Flask shows real HTML web pages.
The problem with returning HTML code
It is possible to return HTML directly from a Python function:
@app.route("/")
def home():
return "<h1>Welcome</h1>"
But in bigger applications this quickly becomes hard to maintain.
What is an HTML template?
A template is an HTML file that Flask uses to show a web page.
Flask uses a template system called Jinja2.
- the HTML is written in a separate file
- Python sends data to the template
- the template generates the final web page
The structure of a Flask project
A typical Flask application looks like this:
project/
app.py
templates/
index.html
An example of a Flask application with a template
First we make an HTML file.
templates/index.html
<html>
<head>
<title>My Flask site</title>
</head>
<body>
<h1>Welcome to my Python website</h1>
</body>
</html>
Then we load the template in the Python code.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
app.run()
How does render_template work?
- Flask finds the HTML file in the templates folder
- it loads the HTML content
- it sends it to the browser as a web page
Mini project – A simple website
Let us make a small application with two pages.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
@app.route("/contact")
def contact():
return render_template("contact.html")
app.run()
How does this project work?
- each route loads its own HTML template
- the browser shows a different page
- the application works like a small website
Related lessons
Frequently asked questions
What is a template in Flask?
A template is an HTML file that Flask uses to show a web page.
What is Jinja2?
Jinja2 is the template engine that Flask uses to generate HTML pages.
Where are the template files?
They are in the templates folder.
Why use a template system?
It makes a web application easier to maintain and organise.
