Flask Templates: Simplifying Web Development
Flask templates are files that define the structure of a web page and allow you to generate dynamic content by inserting data into predefined placeholders.
The templates use the Jinja2 templating engine, which provides a wide range of features that make it easy to create complex web pages.
In this article, you will explore Flask templates with examples and their advantages in web development.
What Are Flask Templates?
In simple terms, Flask templates are HTML files that have spaces for changing content.
We call these spaces template variables, and they are enclosed in double curly braces ({{ }}).
You can make use of these variables to exhibit data that comes from your Flask application, including input from users or information obtained from databases.
You can display the output of a function that is connected to a particular URL as HTML.
In below example, the function named “show_html()” will exhibit “Here’s the html code” with an <h1> heading.
Example: 
Producing HTML content from Python code can be difficult, especially when including variable data and Python language features like loops or conditionals. It would require a lot of switching between HTML and Python.
That’s where the Jinja2 template engine, provided by Flask, comes in handy.
Instead of generating static HTML in the function, you can utilize the “render_template()” function to display an HTML file.
form.html:
Example: 
Execute the following code on python shell:
Example: 
Flask attempts to locate the HTML file in the “templates” directory that is situated in the same folder as the script.
- Application folder
- Greetings.py
- templates
- form.html
A “web templating system” is the process of generating an HTML file that allows dynamic insertion of variable data.
A web template system includes a template engine, a data source, and a template processor.
Flask makes usage of the jinja2 template engine. A web template consists of HTML code with placeholders for variables and expressions (in this case, Python expressions) that are substituted with values when the template is displayed.
The below code is stored as “form.html” in the “templates” directory.
Example: 
In a python shell implement the following code to check template rendering.
Example: 
Once the development server begins running, you can open your browser and enter the following URL: http://localhost:5000/show/MR.Examples
The variable component of the URL is placed in the “{{ name }}” placeholder.
The jinja2 template engine has specific symbols for separating from HTML:
Symbols | Overview |
{% … %} | is used for Statements. |
{{ … }} | is used for Expressions that are displayed in the template output. |
{# … #} | is used for Comments that are not displayed in the template output. |
# … ## | is used for Line Statement |
The above example showcases the utilization of conditional statements within a template. The URL rule directs to the voting_html() function, which takes an integer parameter and passes it to the form.html template. Within the template, the value of the input parameter (age) is compared to 18, and HTML is displayed based on whether it is greater or less than or equal to 18.
The script for the HTML template named form.html is presented below:
Example: 
Below is the Python code to render the form.html:
Example: 
You should take note that the conditional statements if-else and endif are encapsulated in the delimiter {%..%}. After running the Python script, you can check the URL http://localhost/eligiblity/19 and then http://localhost/eligiblity/12 to observe how the HTML output changes conditionally.
Vowel checker HTML file code:
Example: 
Vowel checker Python code file:
Example: 
You can also implement Python loop constructs within the template. When you open the URL http://localhost:5000/courses in your browser, the course() function will provide a list object to the form.html template.
Within the template, a for loop is utilized to render the courses list object as cells within an HTML table.
Following is the code of form.html where the courses list renders:
Example: 
Here’s the Python code for the course list:
Example: 
Once more, you will find that the Python statements that belong to the For loop are encapsulated within {%..%}, while the mrx expressions are contained within {{ }}.
You can also implement Python loop constructs within the template. When you open the URL http://localhost:5000/employee in your browser, the employee_detail() function will provide a dictionary object to the template form.html.
Within the form.html template, a for loop is utilized to display the key and value pairs of the employee{} dictionary object as cells within an HTML table.
To save the HTML script for employee details, you should store it as form.html within the templates directory.
Example: 
form.html Explanation
- The above code is an HTML template file named ‘form.html’ that has been designed to display employee salaries and will work together with the Python Flask web application.
- The HTML template generates a table with a header labeled ‘EMPLOYEE SALARIES’ and two columns named ‘key’ and ‘value’.
- Inside the table, a for loop is utilized to iterate over the dictionary object ’employee’, which was passed in as a parameter to the template file from the Flask application.
- During each iteration of the for loop, the current key and value of the dictionary are assigned to the variables ‘key’ and ‘value’.
- These variables are then used to fill in the cells of the table for each row.
- Once all key-value pairs in the dictionary have been iterated over, the HTML template concludes the loop with the statement {% endfor %}.
- When the Flask application renders the template file, it will display an HTML table that contains the names of employees and their respective salaries.
Execute the following code within the Python shell environment.
Example: 
Example Explanation
Here are the main points of the above Python script:
- The script uses Flask to create a web application with a single route.
- The route is defined using the @app.route decorator and is associated with the URL ‘/employee’.
- When a user visits this URL, the employee_detail function is executed.
- The employee_detail function creates a dictionary called employee_dict that contains the names and salaries of five employees.
- The render_template function is called with two arguments: the name of an HTML template file and a dictionary of variables to populate the template.
- The dictionary of variables passed to render_template contains a single key-value pair, where the key is ’employee’ and the value is the employee_dict dictionary.
- The Flask application is started in debug mode using the app.run() method inside an if name == ‘main‘ block, which ensures that the application is only run if the script is executed directly.
Flask Templates Benefits
- Flask templates enable the separation of presentation layer (HTML/CSS) from application logic (Python code), thereby helping to maintain and update application code without impacting web page appearance.
- Templates promote code reusability across web pages through the use of base templates containing common elements (such as header, footer, and navigation bar), which can be extended in other templates.
- Flask templates provide dynamic content creation capabilities, allowing for the manipulation of data and HTML element generation based on user input or application data using control structures like loops and conditional statements.
- Flask templates can improve web application performance by caching frequently used templates, which reduces server load and improves response time for subsequent requests.
- Flask templates can contribute to a better user experience by helping create a visually appealing and consistent user interface, enabling developers to concentrate on enhancing user experience without worrying about the technical details of HTML and CSS rendering.
Conclusion
If you’re a developer looking to build modern web applications, Flask templates are a powerful feature you should consider using. They allow you to separate the presentation layer from the application logic, making your code easier to maintain and update over time. Additionally, Flask templates enable you to reuse code across multiple web pages, saving you time and reducing the likelihood of errors.
One of the most significant advantages of Flask templates is their ability to generate dynamic content. With Flask templates, you can create web pages that adapt to user input or changing data, resulting in a better user experience. Furthermore, Flask templates can enhance the performance of your web application by reducing the amount of data that needs to be sent to the client.
Overall, Flask templates are a critical tool in building web applications that are manageable, scalable, and visually appealing. By using templates, you can create web applications that are easier to maintain and update over time. Whether you’re building a simple website or a complex web application, Flask templates are an essential component of any Flask project.