DEV Community

Cover image for Rendering HTML in Flask
Hans(Akhil) Maulloo
Hans(Akhil) Maulloo

Posted on

Rendering HTML in Flask

Hello World!
In my previous article, I talked about building the most simple application you can ever build using Flask. In this article, I will write about rendering HTML files instead of return static strings. It will not really matter if you did not read the previous article, because I will build a new application from scratch that renders HTML pages in this article.

Content

  1. Prerequisites
  2. Generate HTML pages
  3. Build flask application
  4. Run the app!

1. Prerequisites

  • Python3
  • Pip3
  • Flask
  • Basics of Html

Directory layout

.
├── app.py
├── templates/
    └── index.html

Before starting, please create a directory as shown above. This will be where we will store all our code.

2. Generate HTML pages

In flask, we use a render_template method to render any HTML page on our browser. This method will, first of all, look for a specific folder in the project's root folder called templates. All your html pages need to be placed in templates so that it can rendered correctly on your browser. Below is a snippet for a simple Hello World which I will write to templates/index.html.

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <h1>Hello World!!</h1>
  </body>
</html>

3. Build flask application

After writing our rendering template, we have to pass this to our backend code for it to know when to return it to the browser. This page can be rendered when the user go to route '/' or '/test'. We need to specify this in our back-end code. Below you will find the snippet for our app.py file.

from flask import Flask, render_template

app = Flask(__name__)

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

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

Compared to previous article, we are importing a render_template method from flask and we are using this method to return our index.html file that we created earlier.

After you set this, you are good to go and run the application.

4. Run the app!

To run the app, simply run

python3 app.py

After that, open up localhost:5000 to see you newly written HTML page.


Thank you for reading and I hope this article was helpful. I will be seeing you in my next article.

Cheers!

Top comments (1)

Collapse
 
mdmarufsarker profile image
Md. Maruf Sarker

Good ❤️