Python Flask HTML Templates – Basic Example

Photo by Christina Morillo from Pexels

Overview

In this quick tutorial we will build a small Python Flask app to render a simple HTML template.

Prerequisites

Install Flask

pip install flask

Templates

IMPORTANT! Create a folder labeled templates. Make sure it is templates and not template. One of the defaults in how Flask renders templates is to look for a folder labeled templates.

Under templates create a file labeled userForm.html. In the form put the following HTML code inside

<pre class="wp-block-syntaxhighlighter-code">&lt;!DOCTYPE html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8"&gt;
        &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
        &lt;title&gt;Flask HTML&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Hello World&lt;/h1&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre>

Python Flask

Create a new python file outside of the templates folder and label it “./app.py

Directory structure should look like the following:

  • templates
    • userForm.html
  • app.py

In the app.py file copy and paste the following code inside.

<pre class="wp-block-syntaxhighlighter-code">from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
   return render_template('simpleform.html')
if __name__ == '__main__':   
   app.run(debug = True)</pre>

Try It

Notice the debug feature is enabled for this example.

Now run the app.

python app.py

You should see the following output.

You can either run the app from clicking on http://127.0.0.1:5000/ or opena breowser and paste http://127.0.0.1:5000/ the URL into it.

That’s it. If you run into any issues, please make sure the HTML file is under the folder templates and the flaskhtml.py is in the root folder just outside of the templates folder.

If you do not want to use templates as the default folder to hold your HTML files then you can use the following in your python app.

app = Flask(__name__, template_folder='YOUR_HTML_TEMPLATE_FOLDER_NAME')