Templating in Flask

Templating in Flask

When it comes to web development the first thing which comes to our mind is HTML. Well HTML is a static file whose content doesn't change when it is rendered.

In Flask there are 2 ways to access an HTML template

String Method

The string method is the most simple way of using HTML in our Flask app. In this method, there is no need of creating an HTML file instead we must return HTML content wrapped up in a string when the path is searched.

Example: Here we will print WELCOME TO HOME PAGE when we are in our default route which is ip:address / . We learn about default routing in previous blogs Check Out

@app.route('/')
 def homepage():
       return '<h1>WELCOME TO HOME PAGE</h1>'

Render Template ()

In the second method, we use the render_template function to render an HTML file. The string method is good to have but it is can be used to process tons of HTML content that is where we use. Here in this method, we need to import render_template() from the flask module. and then use it as a function with the file name.

Before doing this we need to understand how would this function render the HTML file. All our HTML files that will be used in the app should be stored in a Directory/Folder called Templates and this TEMPLATES folder should be stored inside the root Directory/Folder.

This function contains two parameters

  • template_file_name or _list : You must pass the file name in this parameter or list of file (But it only reads the first one)
  • context(optical): You should pass a variable that you are gonna use in the HTML page. We will discuss it in an upcoming blog.
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template('home.html')


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

In the About code, the render_template function fetches the HTML file named home.html from the templates folder and presents it in the default route. We will learn more about templating in further blogs