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 osandimport jinja2inmain.py- Create a directory named
templatesand then use the importedosobject 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
formand put it in a newly createdhello_form.htmlfile in thetemplatesdirectory. - In the
indexfunction, create atemplatevariable that holds the template returned from Jinja'sget_templatefunction 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
helloreturns frommain.pyand put it in a newly createdhello_greeting.htmlfile in thetemplatesdirectory. Be sure to add the proper doctype and head/body tags. - Repeat step 5 for the
hellofunction, but this time pass an argument totemplate.renderthat matches a placeholder callednamein 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=Trueoption:jinja_env = jinja2.Environment( loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
Code
View the final code from this lesson.