Templates in Flask explained and the importance of using them

In this tutorial, we are going to learn about the templates in flask. We are also going to learn how to implement the templates in flask and also the use of the Jinja2 template engine in it.

Flask – Templates

We can generally display the output bound to a function in HTML. For example – in the code given below, the hello() function will print the output as “Hello CodeSpeedy” enclosed in <h1> tags.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
   return '<html><body><h1>Hello CodeSpeedy</h1></body></html>'

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

But still, generating the HTML data from python code would be very tiring and cumbersome, especially when we have to put conditionals and loops into our python code. This would require a subsequent escaping from HTML.

But here comes the Jinja2 template engine to our rescue. It helps us to create separate HTML pages which can be rendered by using the render_template() function.

from flask import Flask
app = Flask(__name__)

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

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

After using the render_template(), flask will look for the HTML file named ‘hello.html‘ in the templates folder at the same project directory where the script is present.

Using the Jinja2 template engine

To use templates in flask first, save the following code in a file named hello.html in the templates folder.

<!doctype html>
<html>
   <body>
   
      <h1>Welcome {{ name }}!</h1>
      
   </body>
</html>

Now, save and run the following python script.

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

@app.route('/hello/<user>')
def hello_name(user):
   return render_template('hello.html', name = user)

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

Then on after starting the development server starts working, open the URL http://localhost:5000/hello/CodeSpeedy.

The variable part of the URL, which in our case is “CodeSpeedy” is inserted at the {{ name }} placeholder.

 

We will talk more about the Jinja2 template engine in the next part of this tutorial. I hope you understood what was explained in this tutorial. If you have any doubts or queries regarding anything explained here, please feel free to comment them down below.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *