HTML templates in flask 4

In this part of the tutorial, you will learn to return HTML pages through your Python script using the flask render_template method. At the end of this lesson, your website will look like this:

flask html templates

As you see, we don’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 of 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. Here is how the web app directory tree should like at this point:

flask directory tree templates folder

So, the Python script stays outside of 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__':

The highlighted lines are the ones to have been 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 associated URL.

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

Great! Let’s expand our website even more.

Leave a comment

Your email address will not be published. Required fields are marked *

4 thoughts on “HTML templates in flask

  • Andre

    When I type this new version of the the web browser keeps showing the previous Hey there string… for some reason when I run the new code with html it is not overwriting it. Any thoughts?

  • Aileen

    guess you don`t have any better idea ..since you complain about my spelling…i am from denmark so it`s not my first language ….. most ppl seem too understand me just fine.. just the trolls always co&#lainingmp8230;mental state??????? what are you talking about????are you sure that your not missed at the local (mental