How to render HTML file in Flask

jaseem CK
TechCrush
Published in
2 min readApr 20, 2020

In last tutorial, we get to know how to run a simple flask app. If you haven’t read those, please go through that and then come back. Let’s leap a little forward. What if we want it to really look like a website, and not just returning random strings. I assume you have the basic knowledge in html. Hypertext Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. So, let’s learn how to make a HTML template in the flask app.

First, create a new folder in the project directory called templates. This naming is important. Now create a new file in the templates folder naming “index.html”. Then insert the below code in the file.

<html>
<head>
<title>Flask Tutorial</title>
</head>
<body>
<h1>This is the Index page</h1>
</body>
</html>

Now, create another file named app.py in the project directory. Then write these codes in to the python file.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()

In this file, we are actually importing render_template function provided by the Flask and then rendering our HTML template, index.html in the home route. Now it is all set to execute. Type python3 app.py in the terminal to run the app.

If everything went well, it will say Running on http://127.0.0.1:5000// . Now we can paste this link in the browser and see the displayed html content. The output will be as follows.

Now that you have learned how to render an html page in flask, you can display any static web pages you want in the flask app. One question that you might have is how to use css, js and images in the web pages. Stay tuned and until then keep routing 😜

--

--

jaseem CK
TechCrush

Coder, Startup enthusiast, Business aspirant, a maker in heart….