Implementing view templates
Jinja2 is the default templating engine of the Flask framework and is used to create HTML, XML, LaTeX, and markup documents. It is a simple, extensive, fast, and easy-to-use templating approach with powerful features such as layout capabilities, built-in programming constructs, support for asynchronous operations, context data filtering, and utility for unit testing.
Firstly, Flask requires all template files to be in the templates
directory of the main project. To change this setting, the Flask()
constructor has a template_folder
parameter that can set and replace the default directory with another one. Our prototype, for instance, has the following Flask instantiation that overrides the default templates directory with a more high-level directory name:
from flask import Flask app = Flask(__name__, template_folder='pages')
In our given setup, the view functions always refer to the pages
directory when calling the template files through the render_template()
method.
When it comes to syntax, Jinja2 has a placeholder ({{ }}
) that renders dynamic content passed by the view functions to its template file. It also has a Jinja block ({% %}
) that supports control structures such as loops, conditional statements, macros, and template inheritance. In the previous route function, assign_exam()
, the GET
transaction retrieves a list of counselor IDs (cids
) and patient IDs (pids
) from the database and passes them to the assign_exam_form.html
template found in the exam
subfolder of the pages
directory. The following snippet shows the implementation of the assign_exam_form.html
view template:
<!DOCTYPE html> <html lang="en"><head><title>Patient's Score Form</title> </head><body> <form action="/exam/score" method="POST"> <h3>Exam Score</h3> <label for="qid">Enter Questionnaire ID:</label> <select name="qid"> {% for id in qids %} <option value="{{ id }}">{{ id }}</option> {% endfor %} </select><br/> <label for="pid">Enter patient ID:</label> <select name="pid"> {% for id in pids %} <option value="{{ id }}">{{ id }}</option> {% endfor %} </select><br/> … … … … … … <input type="submit" value="Assign Exam"/> </form></body> </html>
This template uses the Jinja block to iterate all the IDs and embed each in the <option>
tag of the <select>
component with the placeholder operator.
More about Jinja2 and Flask 3.x will be covered in Chapter 2, but for now, let’s delve into how Flask can implement the most common type of web-based transaction – that is, by capturing form data from the client.