Table of contents
1.
Introduction
2.
Templates
2.1.
Example
2.2.
Templating
3.
Delimiters
3.1.
Example 
3.2.
Embedding Python statements in HTML
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Templates in Flask

Author Parth Jain
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Flask is a python based web framework that allows the creation of a web application in python language with the help of its features and tools.
When a website is under development, Its code can be divided into two categories,
The Presentation Logic
The Business Logic 
The Presentation logic is the code that governs how the browser will display the website, and the Business logic controls all the functionalities the website will perform. 
As an example, let us consider a banking application. The homepage consists of a background, buttons, navigation bar, headers, tables, heading, paragraphs, and images. These components are created using HTML and CSS and are under the presentation logic. All the functionalities come under the business logic when a user login-logout is performed.
In flask, it is possible to return HTML elements. However, this would mean having both presentation and business logic reside in the same file.
This is where Templates are helpful. Instead of returning HTML elements inside the business logic file, we return HTML files directly with the help of the render_template() function.
Furthermore, with Jinja templating language, it is possible to embed if-else statements and loops into an HTML file that provides dynamic functionality to a website. 

Templates

Now that we have a little understanding of Templates, it is time to concentrate our grasp on their use with the help of a practical example.

Example

Consider the app.py file below,
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
   return '<html>
<body>
<h1>Hello User</h1>
<h2>Welcome to Coding Ninjas !</h2>
</body>
</html>'

if __name__ == '__main__':
   app.run(debug = True)
You can also try this code with Online Python Compiler
Run Code

This code renders a Hello User message when the user is in the root route. Now, what if there are multiple routes on a website. The code will become highly cumbersome. 

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return '<html>
<body>
<h1>Hello User</h1>
<h2>Welcome to Coding Ninjas !</h2>
</body>
</html>'

@app.route('/home')
def index():
   return '<html>
<body>
<h1>Hello User</h1>
<h2>Welcome to Coding Ninjas Home Page !</h2>
</body>
</html>'

@app.route('/contact')
def index():
   return '<html>
<body>
<h1>Hello User</h1>
<h2>Welcome to Coding Ninjas Contact Page !</h2>
</body>
</html>'

@app.route('/faq')
def index():
   return '<html>
<body>
<h1>Hello User</h1>
<h2>Welcome to Coding Ninjas FAQ Page !</h2>
</body>
</html>'

if __name__ == '__main__':
   app.run(debug = True)
You can also try this code with Online Python Compiler
Run Code

Returning HTML tags for each route in the same file makes the code look complicated and overwhelming.

Templating

To solve the above problem, we use the render_template(). The render_template function allows us to attach an HTML file instead of writing the entire HTML code in the file.
To use render_template, we need to import it first.
from flask import render_template
Let us create a folder with the name templates in the application directory. This folder will house all the .html files that the render_template function will embed.
In our case let us create a welcome.html file inside the templates folder.

welcome.html

<!doctype html>
<html>
   <body>  
      <h1>Hello User</h1>
<h2>Welcome to Coding Ninjas !</h2>
   </body>
</html>

app.py

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

@app.route('/')
def message():
   return render_template(“welcome.html”)

if __name__ == '__main__':
   app.run(debug = True)
You can also try this code with Online Python Compiler
Run Code

Output:

The above code is less complex and is easy to debug. Using templates were able to separate our presentation logic from the business logic. 

Delimiters

Jinja2 templates provide some Delimiters, a unique sequence of symbols that enable us to create or implement dynamic HTML data representation. The Jinja2 template has assigned specific placeholders for variables and code logic to embed business logic inside the HTML document. This increases the functionality of a static HTML file while drastically decreasing the lines of code and separate file construction.
{% ... %} for statements
{{ ... }} for expressions or to print template output
{# ... #} implements comments that are not included in the final output
# ... ## for line statements
These are the 4 Delimiters provided by the Jinja2 template engine.

Example 

Let us consider a case where we are given a user’s name and provide a welcome message with their name.
We can easily implement this by using Delimiters as we only need to pass the value of the username inside a variable, and using the {{ }} template, Delimeters embed the username on the welcome.html file.

app.py

from flask import *  
app = Flask(__name__)  
  
@app.route('/user/<username>')  
def message(username):  
      return render_template('welcome.html',user=username)  
if __name__ == '__main__':  
   app.run(debug = True)  
You can also try this code with Online Python Compiler
Run Code

welcome.html

<!doctype html>
<html>  
<head>  
<title>Message</title>  
</head>  
<body>  
<h1>Hello, {{ user}}!</h1>
<h2>Welcome to Coding Ninjas!</h2>   
</body>  
</html>  

Embedding Python statements in HTML

HTML files are meant only for design purposes, and thus we can not perform logical operations in them. However, there are instances when we want to render data from an HTML file upon a specific condition. To implement logical procedures inside an HTML file Jinja2 template, prove the {% %} Delimiters that make writing dynamic HTML files easy.
Let us consider a case where we are given a user’s age as input and display whether the user is a senior citizen. Without using Jinja2 delimiters, we will need to create two .html files that contain outputs for both cases, and in our business logic, we will need to embed both the files with an if-else statement. Creating separate .html files for each case will again be cumbersome and time-consuming. Therefore, we make a single .html file and use Delimiters to apply our business logic.

app.py

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

@app.route('/verify/<int:input>')
def verify(input):
   return render_template('verification.html', age= input)

if __name__ == '__main__':
   app.run(debug = True)
You can also try this code with Online Python Compiler
Run Code

verification.html 

<!doctype html>
<html>
   <body>
      {% if age>=60 %}
         <h1> You are a Senior Citizen !</h1>
      {% else %}
         <h1>You are not a Senior Citizen</h1>
      {% endif %}
   </body>
</html>

verification.html will render output upon the input received while saving us the hassle of creating two files.

Click here to know about, PHP For Loop

FAQs

  1. How do I create a template in Flask?
    To create a template in Flask, you need to import the render_template() function. This function looks for HTML files inside the templates folder created manually inside the application directory. 
     
  2. Jinja2 provides how many Delimiters in Flask?
    Jinga2 provides 4 kinds of Delimiters in Flask:
    {% ... %} for statements
    {{ ... }} for expressions or to print template output
    {# ... #} implements comments that are not included in the final output
    # ... ## for line statements
    These are the 4 Delimiters provided by the Jinja2 template engine.

Key Takeaways

In this article, we learned about Templates in Flask and how they help separate the business logic from the presentation logic. We also learned about Delimiters that enable logical conditions inside an HTML document. However, this isn't enough, as there is always much more to explore and learn about this vast field of Web Development. To know more about Flask and its intricacies, check out the articles on Flask or enroll in our highly curated Web Development course.      

Live masterclass