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.
- Generate HTML pages
- Build flask application
- Run the app!
- Basics of Html
. ├── app.py ├── templates/ └── index.html
Before starting, please create a directory as shown above. This will be where we will store all our code.
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>
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.
To run the app, simply run
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.