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:
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:
<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:
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:
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__)
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 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.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
We will keep you Python-motivated if you subscribe below.