Using render_template
In this lesson we introduce a shortcut to rendering Jinja2 templates, using Flask's render_template function. We will refactor the main.py in our hello-flask directory to use this shortcut. When you use render_template, you can eliminate a lot of the code that we have been using. You can use this shortcut function as long as all your templates are in the templates/ directory and you want a setting of autoescape=True (which is built into render_template).
Here are the steps to using render_template:
- Import it:
from flask import Flask, request, redirect, render_templateThis import of
render_templatereplaces the need to import jinja2 and the need to construct thetemplate_dirvariable and create a template loader, as we did with the following code:template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment( loader = jinja2.FileSystemLoader(template_dir), autoescape=True)Note that using
render_templaterequires you to put your templates in a directory namedtemplates, while our initial, more hands-on approach allowed us to specify where our templates are located. - Call
render_template:return render_template('hello_greeting.html', name=first_name)This call to
render_templatereplaces the two calls below (using thehellofunction as an example):template = jinja_env.get_template('hello_greeting.html') return template.render(name=first_name)