Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Jinja2 templates to render HTML in Flask


    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


    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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."