HTML templates in flask 2


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>
<html>
<body>
<h1>My Personal Website</h1>
<p>Hi, this is my personal website.</p>
</body>
</html>

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__)

@app.route('/')
def home():
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)

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 *

2 thoughts on “HTML templates in flask

  • Andre

    When I type this new version of the hello.py 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?