Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
Flask - Templates
Next article icon

Flask - Templates

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to learn about the flask templates in Python.

Python is a high-level, open-source, object-oriented language, consisting of libraries, used in many domains, such as Web Development, Machine Learning, and so on. In web development, Python is used for building REST APIs, server-side apps, etc. Popular libraries, are Django, Flask, Web2Py, etc.

Flask is a simple, speedy, scalable library, used for building, compact web applications. It is a micro framework, that allows developers, with useful tools and features, for coding REST APIs, and backend data processing, of web apps.

Prerequisites

  • Install Python, PyCharm, or any other IDE.
  • Install the Flask module.
  • Basic understanding of HTML language.
  • Basic familiarity with Flask.

Creating a basic flask app

To create a flask application firstly import a flask and then create a flask instance after that create a default route using a decorator in python. Create a function that returns a string that is displayed on the webpage. Start the flask web app with debug mode on.

Python3
# import the Flask library from flask import Flask   # Create the Flask instance and pass the Flask # constructor, the path of the correct module app = Flask(__name__)   # Default route added using a decorator, for view function 'welcome' # We pass a simple string to the frontend browser @app.route('/') def welcome():     return "Hello! Let us learn about importance of Exercise!"   # Start with flask web app, with debug as True,# only if this is the starting page if(__name__ == "__main__"):     app.run(debug=True) 

Output:

Flask - Templates
 

What is Flask Template?

A flask template is a template of a webpage that can be used by web developers to reduce the hectic work of writing the code for each webpage of a website. For example, web developers can create a template that has headers like a navbar and footer which is the same for all web pages. so instead of writing code for the header and footer of every webpage, we can use that template.

render_template() method

The render_template() method, allows us to fetch the HTML files, and, pass them to the browser. Hence, instead of rendering, raw string or inline HTML code, from the backend code to the browser, we can have a separate HTML file, passed to the client. The steps followed, to use the same, are as follows.

Step 1: Create a folder called 'templates', in the same directory level, as the Python code files. Please note, that the folder name should be 'templates', and, any other name, would not allow for the functionality to work properly.

Step 2: Add all the HTML files, of the application to the templates folder. 

Step 3: We will create 'exercise.html', an HTML page, and add this file, to the templates folder. The file, returns an Exercise importance message, with some extra HTML code.

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Importance of Exercise</title> </head> <body>  <h1> Benefits of Exercise!</h1>  <ul>Let us understand -     <li>Helps in  Controlling Weight</li>     <li>Helps in Combating Diseases</li>     <li>Boosts Energy</li> </ul>  </body> </html> 

The templates folder structure looks as shown, in the image below.

Flask - Templates
 

Step 4: In Python code, we will first add, the import for the render_template() method.

Step 5: Now instead of returning a raw string, we will return the HTML file, present in the templates folder, for the URL 'http://localhost:5000/'. In the method render_template(), we will pass the HTML file name, to be rendered as an argument.

Python3
# import the Flask library # import render_template method  from flask import Flask, render_template  # Create the Flask instance, and, pass the Flask # constructor, the path of the correct module app = Flask(__name__)  # Default route added using a decorator, # for view function 'welcome' @app.route('/') def welcome(): # Use render_template() and pass the HTML file name, # to be rendered, to the browser. # The file should be present, in the 'templates' folder.     return render_template("exercise.html")  # Start with flask web app, with debug as True, # only if this is the starting page if(__name__ == "__main__"):     app.run(debug=True) 

Output: 

Flask - Templates
 

Adding Dynamic Information with Templates

We can use, the render_template() method, to send dynamic data, to the front end(HTML file), from the Python code. Similarly, variables, lists, and, so on can also be passed, from the Python code. To do so, we will make use of 'Expressions' statements, in the HTML file. Let us add, another view function, walking(), and pass variable values, of time and calories, to the front end side. Add file 'walking.html' in the templates folder. The Python code now looks as follows:

Python3
# import the Flask library # import the render_template method from flask import Flask, render_template   # Create the Flask instance and pass the Flask # constructor, the path of the correct module app = Flask(__name__)   # Default route added using a decorator, # for view function 'welcome' # Landing page of our web application - exercise.html @app.route('/') def welcome():      return render_template("exercise.html")   # Walk route, added using a decorator, # for view function 'walking' # Render template 'walking.html' and, # pass values of time and calories, in key-value pairs. @app.route('/walk') def walking():         return render_template("walking.html",                            time=30,                            calories=150)   # Start with flask web app, with debug as True, # only if this is the starting page if(__name__ == "__main__"):     app.run(debug=True) 

Explanation: In the above code, we added a new view function, walking(),  corresponding to the route '/walk'. The view function renders the 'walking.html' file (added in the templates folder). Apart from that, we are passing the values of time and calories, to the HTML side, in key-value pair format. The 'time' and 'calories' are keys, and, will be used on the HTML side, for substituting appropriate values. 

The HTML side code now looks as follows:

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Benefits of Walking!</title> </head> <body> <p>Physical activity, such as walking,   is important for weight control because it   helps you burn calories. </p><br> If you add {{time}} minutes of brisk   walking to your daily routine,   you could burn about {{calories}} more calories a day. </body> </html> 

Explanation: In the code above, we have made use of Expression statements. They should have, two sets of curly brackets {{}}, and, the key passed by the backend, in between. So it looks like {{time}} or {{calories}}. The key name should be exactly the same, as present on the backend side.

Output:

Flask - Templates
 

Making Decisions, Adding loops Using Expressions and Templates

Apart from sending variable values, we can send a list, add for loops, and, make decisions as well, using the Expressions statements. To do so, let us add, code snippets for the same, on Python and HTML side, as shown below:

Python3
# import the Flask library from flask import Flask, render_template   # Create the Flask instance and pass the Flask # constructor, the path of the correct module app = Flask(__name__)  # declare a todo list of gym to pass to the frontend file joiningGym = ['Rent a Car','Buy Gym clothes',               'Check for Gym Location','Meet the Trainer']  # Default route added using a decorator, # for view function 'welcome' # Landing page of our web application-exercise.html @app.route('/') def welcome():         return render_template("exercise.html")  # Default route added using a decorator, # for view function 'walking' # renders the page 'walking.html' @app.route('/walk') def walking():     return render_template("walking.html",                            time=30,                            calories=150)  # Route added using a decorator, # for view function 'joingym' # Pass the list of todo's and decidegym  # boolean variable, to the HTML file @app.route('/gym') def joingym():     return render_template("joingym.html",                            todo=joiningGym,                            decidegym=True)  # Start with flask web app, with debug as True, # only if this is the starting page if(__name__ == "__main__"):     app.run(debug=True) 

The corresponding  'joingym.html' file, is as shown below:

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Joining the Gym</title> </head> <body>  <h1> Do you want to join the Gym?</h1> {% if decidegym %} <ul>{% for item in todo %}     <li>{{item}}</li>     {% endfor %} </ul> {% else %} <p> No problem ! Look for other      Exercise options that suits you!</p> {% endif %}  </body> </html> 

Let us understand the Python and HTML code files:

  • In the Python code, we have added a new view function 'joingym'. The view function renders, the 'joingym.html' file, for the route 'http://localhost:5000/gym', invoked from the browser. 
  • We have prepared a todo list, while joining the gym, in the list variable 'joiningGym'.  We are passing the list, to the frontend file, along with the 'decidegym'  boolean variable. 
  • In the HTML file, if the decidegym variable, has the value True, then the todo list elements, are displayed. It means the if block code executes.
  • If it is False, then the Else block is executed, which then displays, the message.
  • The for loop and if-else decision logic is written, using Expression statements. They are written in curly brackets {% %} as shown in the HTML file.

Output: When 'decidegym' variable value is passed as True, while passing values in render_template() method, of view function joingym().

Flask - Templates
 

When 'decidegym' variable value is passed as False, while passing values in render_template() method, of view function joingym().

Flask - Templates
 

Next Article
Flask - Templates

P

phadnispradnya
Improve
Article Tags :
  • Python
  • Python Flask
Practice Tags :
  • python

Similar Reads

    FastAPI - Templates
    FastAPI is a modern web framework that is relatively fast and used for building APIs with Python 3.7+ based on standard Python type hints. In this article, we will delve deeper into learning how to integrate HTML templates and CSS style sheets with our FastAPI. Integrate Templates with FastAPIFastAP
    5 min read
    Flask Rendering Templates
    Flask is a lightweight Python web framework that enables developers to build web applications easily. One of its key features is template rendering, which allows dynamic content generation using Jinja2 templating. In this guide, we'll explore how to render templates in Flask.Setting up FlaskSetting
    6 min read
    Django Templates
    Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
    7 min read
    Django Templates | Set - 1
    There are two types of web pages - Static and Dynamic pages. Static webpages are those pages whose content is static i.e. they don't change with time. Every time you open that page, you see the same content. Their content is independent of time, location, user, etc. Dynamic webpages are those pages
    2 min read
    Meteor Templates
    Meteor is a full-stack JavaScript platform that is used for developing modern web and mobile applications. Meteor has a set of features that are helpful in creating a responsive and reactive web or mobile application using JavaScript or different packages available in the framework. It is used to bu
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences