Generating Secure Dynamic Templates with Jinja2

FlaskFlaskBeginner
Practice Now

Introduction

Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping with escape on your own to keep the application secure. Because of that Flask configures the Jinja2 template engine for you automatically. Templates can be used to generate any type of text file. For web applications, you’ll primarily be generating HTML pages, but you can also generate markdown, plain text for emails, and anything else.

In this lab, we will learn how to use Jinja2 template engine to generate secure and dynamic templates.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL flask(("`Flask`")) -.-> flask/CoreConceptsGroup(["`Core Concepts`"]) flask(("`Flask`")) -.-> flask/DataHandlingGroup(["`Data Handling`"]) flask(("`Flask`")) -.-> flask/DevelopmentToolsGroup(["`Development Tools`"]) flask/CoreConceptsGroup -.-> flask/application_object("`Application Object`") flask/DataHandlingGroup -.-> flask/response_objects("`Response Objects`") flask/DevelopmentToolsGroup -.-> flask/template_rendering("`Template Rendering`") subgraph Lab Skills flask/application_object -.-> lab-188849{{"`Generating Secure Dynamic Templates with Jinja2`"}} flask/response_objects -.-> lab-188849{{"`Generating Secure Dynamic Templates with Jinja2`"}} flask/template_rendering -.-> lab-188849{{"`Generating Secure Dynamic Templates with Jinja2`"}} end

Render Templates with Jinja2

In this step, you will implement template rendering with the Jinja2 template engine.

  1. Open the rendering_templates.py file and first import the Flask class and render_template. Then create an instance of the Flask class.
from flask import Flask, render_template
app = Flask(__name__)
  1. Next we use the route() decorator to create two routes, / and /<name>, for sharing one view function called hello. To render a template you can use the render_template() method. It is provided by Flask for rendering templates with the Jinja2 template engine. All you have to do is to provide the name of the template and the variables you want to pass to the template engine as keyword arguments. In the view function, we use the render_template() method to render the template hello.html with a variable called name.
@app.route('/')
@app.route('/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
  1. Creating a main entry point of the script for starting the Flask application at a port(e.g. port=5000). Then enabling the debug mode.
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
  1. Flask will look for templates in the templates folder defautly. So we need to create a folder named templates and create the file named hello.html under that folder. We can create the required folder and file by executing the following command in the terminal.
cd ~/project
mkdir templates
cd templates
touch hello.html
  1. Open the templates/hello.html file and write the following codes:
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}

Above codes use the conditional block in Jinja2. It checks whether the name variable is truthy (not None or empty). If it is, the content Hello {{ name }}! will be displayed. Otherwise, the content Hello, World! will be displayed.

  1. To run the application, first using the following commands to launched the Flask application in the terminal:
cd ~/project
python3 rendering_templates.py
  1. Then open the "Web 5000" tab located at the top of the interface, and refresh the interface. And then you should see the page displays Hello, World!.
example_image
example_image
  1. For route /<name>, you can add a suffix directly in the URL bar above. For example, Below is a suffix flask entered in the URL bar with port 5000, and it displays Hello, flask! as its output.

    example_image
    You can try different /<name> path to the URL bar, the output will also be changed correspondingly.

Summary

In this lab, we learnt how to render our templates using the Jinja2 template engine by using the render_template() method. This method not only renders templates vividly, but also enables automatic escaping, which helps prevent potential XSS attacks.

Other Flask Tutorials you may like