In this tutorial, we are going to see the Flask simple HTML Templates, this is going to be something the extension work of the previous HelloWorld example.

Flask HTML Templates:

In the previous example, we return the Hello, World! string message from the server, but in reality, the server sends an HTML response to a web browser. So as part of this tutorial, I am going to return the HTML response from the Flask server.

Version:

  • Python 3.8.5
  • Flask 2.0.1
  • Mac OS X

Application Structure:

My current application structure

(venv) flask-templates %
.
├── app
│   ├── __init__.py
│   └── routes.py
└── helloworld.py

You might have noticed that I just copied our Hello World application 🙂 and building some interesting webpage.

implement routes.py

app/routes.py
from app import app

@app.route('/')
def index():
    return """
    <html>
    <head>
    <title>Colorful Hello, World!</title>
    </head>
    <body>
    <h1 style="color:#093657"> Hello, World!</h1>
    </body>
    </html>
    """

This is a very basic HTML page with a head and body section, inside there is a title that will appear on the browser tab and in the body, I show the content with color code. I left the remaining files as it is.

__init__.py

app/__init__.py
from flask import Flask

app = Flask(__name__)

from app import routes

helloworld.py

flask-templates/helloworld.py
from app import app

Run the application:

Make sure you have to set the FLASK_APP=helloworld.py environment variable.

Flask HTML Templates Example

Now let’s some more extend this application by appending the user name. In this case, I am creating a fake user with a python dictionary but in reality, it’s going to be a real user that’s being populated from the database or somewhere else.

app/routes.py
from app import app

@app.route('/')
def index():
    user = {
        'name':'Chandra'
    }
    return '''
    <html>
    <head>
    <title>Colorful Hello, World!</title>
    </head>
    <body>
    <h1 style="color:#093657"> Hello, World! '''+user['name']+'''</h1>
    </body>
    </html>
    '''

Output:

Flask HTML Templates Example - dict

Problem with this approach:

So far so good, but think about a little bit more, that this is one of the simplest pages that we build so far and yet we already have a little bit of complication in the way that we present a variable component user['name']inside the page. If we continue to extend this page it’s going to become very difficult to maintain and the problem is going to even worse when we start adding more pages.

The big problem here is that we are mixing code with HTML and that’s really a disaster, so with this, we clearly say it is not a good practice.

Good Practice:

Surely the accepted good practice is to separate the application logic from presentation. So what I am going to do now is; I’ll move the HTML into a separate file, so that’s where the templates come into place.

Flask HTML Templates:

By default, Falsk is going to look the templates into the directory named templates so hence I am going to create a directory called templates inside the application folder that is app

Updated project strucure:

(venv) flask-templates %
.
├── app
│   ├── __init__.py
│   ├── routes.py
│   └── templates
│       └── index.html
└── helloworld.py

Create index.html

app/templates/index.html
<html>
    <head>
        <title>Colorful Hello, World!</title>
    </head>
    <body>
        <h1 style="color:#093657"> Hello, Template! {{user.name}}</h1>
    </body>
</html>

On the above for the user.name I have to enclose this with double curly braces like this  {{user.name}} we can call it as template placeholders. At the time we produce a response from a browser, we are going to replace that with actual values it’s going to come from a user object.

update routes.py

In routes.py remove the static HTML content and instead call render_template() function that comes with Flask.

app/routes.py
from app import app
from flask import render_template

@app.route('/')
def index():
    user = {
        'name':'Chandra'
    }
    return render_template('index.html', user = user)

Make sure we have to pass the template name and user object as parameters for render_template() function.

Let’s run again

Flask Simple HTML Templates Example templates file

References:

Happy Learning 🙂