Tuesday, November 19, 2024
Google search engine
HomeLanguagesFlask – Templates

Flask – Templates

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

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

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments