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: 

from flask import Flask app = Flask(__name__)@app.route('/') def show_html(): return "<html><body><h1>Here's the html code</h1></body></html>" if __name__ == '__main__': app.run(debug = True)

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: 

<html> <body> <center><h1>MR.EXAMPLES</h1></center> <center><h3>Flask Tutorial</h3></center> </body> </html>

Execute the following code on python shell:

Example: 

from flask import Flask, render_template app = Flask(__name__)@app.route('/') def show_html(): return render_template('form.html') if __name__ == '__main__': app.run(debug = True)

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: 

<html> <body> <center><h1>The best programming website in the world is: {{name}}</h1></center> </body> </html>

In a python shell implement the following code to check template rendering.

Example: 

from flask import Flask, render_template app = Flask(__name__)@app.route('/show/<mrx>') def show_html(mrx): return render_template('form.html', name = mrx) if __name__ == '__main__': app.run(debug = True)

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:

SymbolsOverview
{% … %}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: 

<html> <body> <center><h1>Vote Casting Checker</h1></center> {% if mrx>=18 %} <h3>Status: </h3><p>Eligible for Voting!</p> {% else %} <h3>Status: </h3><p>Not Eligible for Voting!</p> {% endif %} </body> </html>

Below is the Python code to render the form.html:

Example: 

from flask import Flask, render_template app = Flask(__name__)@app.route('/eligiblity/<int:age>') def voting_html(age): return render_template('form.html', mrx = age) if __name__ == '__main__': app.run(debug = True)

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: 

<html> <body> <center><h1>Vowel Checker</h1></center> {% if vowel.lower()==('a'or'e'or'i'or'o'or'u') %} <h3>Status: </h3><p>Its a Vowel</p> {% else %} <h3>Status: </h3><p>Not a Vowel</p> {% endif %} </body> </html>

Vowel checker Python code file:

Example: 

from flask import Flask, render_template app = Flask(__name__)@app.route('/checker/<char>') def vowel_html(char): return render_template('form.html', vowel = char) if __name__ == '__main__': app.run(debug = True)

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: 

<html> <body> <h2>COURSE LIST</h2> {% for mrx in course %} <p>{{mrx}}</p> {% endfor %} </body> </html>

Here’s the Python code for the course list:

Example: 

@app.route('/courses') def course(): course_list = ['Data Structures','Object Oriented Programming','Database Management System','Design Analysis Alogrithm','Probability Statistics'] return render_template('form.html', course = course_list) if __name__ == '__main__': app.run(debug = True)

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: 

<!doctype html> <html> <body> <h1>EMPLOYEE SALARIES</h1> <table border = 4> {% for key, value in employee.items() %} <tr> <th width = 150px> {{ key }} </th> <td width = 150px> {{ value }} </td> </tr> {% endfor %} </table> </body> </html>

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: 

from flask import Flask, render_template app = Flask(__name__)@app.route('/employee') def employee_detail(): employee_dict = {'Harry':'2000$','Dustin':'1000$','Tory':'900$','Kate':'1700$','Alyssa':'1500$'} return render_template('form.html', employee = employee_dict) if __name__ == '__main__': app.run(debug = True)

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.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

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