Using Jinja2 Templates in Flask
Notes
In this video we learn how to make our code more maintainable and encapsulated by removing the long strings of HTML from our main.py
and putting them into templates. We will do this using a Python templating engine called Jinja2. Here are the steps we'll follow:
import os
andimport jinja2
inmain.py
- Create a directory named
templates
and then use the importedos
object to construct a string that contains the file path to this directory. Note that this path will be an absolute path in the filesystem on which the program is running.template_dir = os.path.join(os.path.dirname(__file__), 'templates')
- Initialize the Jinja templating environment, using the
template_dir
:jinja_env = jinja2.Environment( loader = jinja2.FileSystemLoader(template_dir))
- Extract the HTML string in the variable
form
and put it in a newly createdhello_form.html
file in thetemplates
directory. - In the
index
function, create atemplate
variable that holds the template returned from Jinja'sget_template
function and then return the string thattemplate.render()
returns:def index(): template = jinja_env.get_template('hello_form.html') return template.render()
- Extract the HTML string that
hello
returns frommain.py
and put it in a newly createdhello_greeting.html
file in thetemplates
directory. Be sure to add the proper doctype and head/body tags. - Repeat step 5 for the
hello
function, but this time pass an argument totemplate.render
that matches a placeholder calledname
in the template itself:def hello(): first_name = request.form['first_name'] template = jinja_env.get_template('hello_greeting.html') return template.render(name=first_name)
- Protect your code from malicious users by adding HTML escaping via Jinja's
autoescape=True
option:jinja_env = jinja2.Environment( loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
Code
View the final code from this lesson.