HTML templates in flask

In this part of the tutorial, you will learn to return HTML pages through your Python script using the flask render_template method.

We won’t have plain text anymore, but text with various formats. That is made possible by returning an HTML template instead of a plain Python string.

Let’s see how I did that.

Create an empty file, name it something like home.html and put the following HTML code inside it:

<!DOCTYPE html>
<h1>My Personal Website</h1>
<p>Hi, this is my personal website.</p>

As you already know, HTML is a markup language used to render webpages. Try to remember these three things about creating HTML pages:

  • An HTML document must start with a declaration that specifies the document type: <!DOCTYPE html>.
  • The HTML document itself always begins with <html> and ends with </html>.
  • The visible part of the HTML document is between <body> and </body>. The area outside that is used to reference Javascript files, CSS, or other features.

The flask framework has been written in a way so that it looks for HTML template files in a folder that should be named templates. So, you should create such an empty folder and then put all the HTML templates in there. 

So, the Python script stays outside the templates folder.

Let’s now edit the Python code so that it reads the HTML template and returns it to the webpage. Here is the updated version:

from flask import Flask, render_template
app = Flask(__name__)
def home():
    return render_template('home.html')
if __name__ == '__main__':

Line 5 was the one that was updated. And what we did is we imported the render_template method from the flask framework, and then we passed an HTML file to that method. The method will generate a jinja2 template object out of that HTML and return it to the browser when the user visits the associated URL.

So, going to localhost:5000 now should display the webpage shown in the screenshot at the beginning of this lesson.

Great! Let’s expand our website even more.

Next Lecture
Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.