Use Jinja2 templates to render HTML in Flask

Will Button
InstructorWill Button
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

In this lesson, you'll get a quick introduction on how to use Jinja2 templates to render HTML using a Flask server in Python. Topics covered:

  • Where to store your HTML templates
  • How to pass variables to the Jinja2 template
  • How to render the resulting HTML in Flask

Instructor: [00:01] If you start writing your html that your web server returns as a string in Python, you're going to start to hate life and your life choice is pretty quick.

[00:08] One of the things that we can do in Flask is create this folder called Templates. Within that Templates folder, we can then create an html file like Hello.html.

[00:20] This allows us to use our editor or any html supplied to us and edit that html file with the full advantage of syntax highlighting and auto-completion, all the great stuff that you get.

[00:31] This html is going to get rendered as a Jinja2 template, which means we can take full advantage of all the Jinja2 features. For example, conditional statements to check if a variable called the name exists.

[00:45] If the parameter name exists, we can render out the value of that parameter in the html of our template. If the name parameter is not there, we can take a completely different action, and then we can close out our conditional logic in the template.

[01:03] Back in our application logic. I am going to create a new route decorator that response to the /hello. without the parameter at the end of it.

[01:15] Just to be consistent with the parameter name we use in our Jinja template, I'll rename user to the parameter name here. Now, instead of returning the string, I am going to return render template, and provide it the name of the template file to return as well as any parameters that the template should have access to.

[01:36] For that to work, from Flask, we need to import the render template function. If I save that and then go to the hello. with no additional parameters attached, that's going to blow up because we called the, say, hello function but didn't include the required parameter of name.

[01:56] We can get around that by giving name a default value of none. Now, when we call it again, we get "Hello, unnamed person," which was rendered by the Jinja template in our Hello.html file.

[02:11] If I call it by adding /will to the end of it, it recognizes that it's a name parameter and responses with "Hello, Will."