2017-12-12T16:29:38Z

The Flask Mega-Tutorial Part II: Templates

In this second installment of the Flask Mega-Tutorial series, I'm going to discuss how to work with templates.

For your reference, below is a list of the articles in this series.

Note 1: If you are looking for the legacy version of this tutorial, it's here.

Note 2: If you would like to support my work on this blog, or just don't have patience to wait for weekly articles, I am offering the complete version of this tutorial packaged as an ebook or a set of videos. For more information, visit courses.miguelgrinberg.com.

After you complete Chapter 1, you should have a fully working, yet simple web application that has the following file structure:

microblog\
  venv\
  app\
    __init__.py
    routes.py
  microblog.py

To run the application you set the FLASK_APP=microblog.py in your terminal session, and then execute flask run. This starts a web server with the application, which you can open by typing the http://localhost:5000/ URL in your web browser's address bar.

In this chapter you will continue working on the same application, and in particular, you are going to learn how to generate more elaborate web pages that have a complex structure and many dynamic components. If anything about the application or the development workflow so far isn't clear, please review Chapter 1 again before continuing.

The GitHub links for this chapter are: Browse, Zip, Diff.

What Are Templates?

I want the home page of my microblogging application to have a heading that welcomes the user. For the moment, I'm going to ignore the fact that the application does not have the concept of users yet, as this is going to come later. Instead, I'm going to use a mock user, which I'm going to implement as a Python dictionary, as follows:

user = {'username': 'Miguel'}

Creating mock objects is a useful technique that allows you to concentrate on one part of the application without having to worry about other parts of the system that don't exist yet. I want to design the home page of my application, and I don't want the fact that I don't have a user system in place to distract me, so I just make up a user object so that I can keep going.

The view function in the application returns a simple string. What I want to do now is expand that returned string into a complete HTML page, maybe something like this:

app/routes.py: Return complete HTML page from view function

from app import app

@app.route('/')
@app.route('/index')
def index():
    user = {'username': 'Miguel'}
    return '''
<html>
    <head>
        <title>Home Page - Microblog</title>
    </head>
    <body>
        <h1>Hello, ''' + user['username'] + '''!</h1>
    </body>
</html>'''

If you are not familiar with HTML, I recommend that you read HTML Markup on Wikipedia for a brief introduction.

Update the view function as shown above and give the application a try to see how it looks in your browser.

Mock User

I hope you agree with me that the solution used above to deliver HTML to the browser is not good. Consider how complex the code in this view function will become when I have the blog posts from users, which are going to constantly change. The application is also going to have more view functions that are going to be associated with other URLs, so imagine if one day I decide to change the layout of this application, and have to update the HTML in every view function. This is clearly not an option that will scale as the application grows.

If you could keep the logic of your application separate from the layout or presentation of your web pages, then things would be much better organized, don't you think? You could even hire a web designer to create a killer web site while you code the application logic in Python.

Templates help achieve this separation between presentation and business logic. In Flask, templates are written as separate files, stored in a templates folder that is inside the application package. So after making sure that you are in the microblog directory, create the directory where templates will be stored:

(venv) $ mkdir app/templates

Below you can see your first template, which is similar in functionality to the HTML page returned by the index() view function above. Write this file in app/templates/index.html:

app/templates/index.html: Main page template

<html>
    <head>
        <title>{{ title }} - Microblog</title>
    </head>
    <body>
        <h1>Hello, {{ user.username }}!</h1>
    </body>
</html>

This is a mostly standard, very simply HTML page. The only interesting thing in this page is that there are a couple of placeholders for the dynamic content, enclosed in {{ ... }} sections. These placeholders represent the parts of the page that are variable and will only be known at runtime.

Now that the presentation of the page was offloaded to the HTML template, the view function can be simplified:

app/routes.py: Use render\_template() function

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    user = {'username': 'Miguel'}
    return render_template('index.html', title='Home', user=user)

This looks much better, right? Try this new version of the application to see how the template works. Once you have the page loaded in your browser, you may want to view the source HTML and compare it against the original template.

The operation that converts a template into a complete HTML page is called rendering. To render the template I had to import a function that comes with the Flask framework called render_template(). This function takes a template filename and a variable list of template arguments and returns the same template, but with all the placeholders in it replaced with actual values.

The render_template() function invokes the Jinja2 template engine that comes bundled with the Flask framework. Jinja2 substitutes {{ ... }} blocks with the corresponding values, given by the arguments provided in the render_template() call.

Conditional Statements

You have seen how Jinja2 replaces placeholders with actual values during rendering, but this is just one of many powerful operations Jinja2 supports in template files. For example, templates also support control statements, given inside {% ... %} blocks. The next version of the index.html template adds a conditional statement:

app/templates/index.html: Conditional statement in template

<html>
    <head>
        {% if title %}
        <title>{{ title }} - Microblog</title>
        {% else %}
        <title>Welcome to Microblog!</title>
        {% endif %}
    </head>
    <body>
        <h1>Hello, {{ user.username }}!</h1>
    </body>
</html>

Now the template is a bit smarter. If the view function forgets to pass a value for the title placeholder variable, then instead of showing an empty title the template will provide a default one. You can try how this conditional works by removing the title argument in the render_template() call of the view function.

Loops

The logged in user will probably want to see recent posts from connected users in the home page, so what I'm going to do now is extend the application to support that.

Once again, I'm going to rely on the handy fake object trick to create some users and some posts to show:

app/routes.py: Fake posts in view function

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    user = {'username': 'Miguel'}
    posts = [
        {
            'author': {'username': 'John'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author': {'username': 'Susan'},
            'body': 'The Avengers movie was so cool!'
        }
    ]
    return render_template('index.html', title='Home', user=user, posts=posts)

To represent user posts I'm using a list, where each element is a dictionary that has author and body fields. When I get to implement users and blog posts for real I'm going to try to preserve these field names as much as possible, so that all the work I'm doing to design and test the home page template using these fake objects will continue to be valid when I introduce real users and posts.

On the template side I have to solve a new problem. The list of posts can have any number of elements, it is up to the view function to decide how many posts are going to be presented in the page. The template cannot make any assumptions about how many posts there are, so it needs to be prepared to render as many posts as the view sends in a generic way.

For this type of problem, Jinja2 offers a for control structure:

app/templates/index.html: for-loop in template

<html>
    <head>
        {% if title %}
        <title>{{ title }} - Microblog</title>
        {% else %}
        <title>Welcome to Microblog</title>
        {% endif %}
    </head>
    <body>
        <h1>Hi, {{ user.username }}!</h1>
        {% for post in posts %}
        <div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
        {% endfor %}
    </body>
</html>

Simple, right? Give this new version of the application a try, and be sure to play with adding more content to the posts list to see how the template adapts and always renders all the posts the view function sends.

Mock Posts

Template Inheritance

Most web applications these days have a navigation bar at the top of the page with a few frequently used links, such as a link to edit your profile, to login, logout, etc. I can easily add a navigation bar to the index.html template with some more HTML, but as the application grows I will be needing this same navigation bar in other pages. I don't really want to have to maintain several copies of the navigation bar in many HTML templates, it is a good practice to not repeat yourself if that is possible.

Jinja2 has a template inheritance feature that specifically addresses this problem. In essence, what you can do is move the parts of the page layout that are common to all templates to a base template, from which all other templates are derived.

So what I'm going to do now is define a base template called base.html that includes a simple navigation bar and also the title logic I implemented earlier. You need to write the following template in file app/templates/base.html:

app/templates/base.html: Base template with navigation bar

<html>
    <head>
      {% if title %}
      <title>{{ title }} - Microblog</title>
      {% else %}
      <title>Welcome to Microblog</title>
      {% endif %}
    </head>
    <body>
        <div>Microblog: <a href="/index">Home</a></div>
        <hr>
        {% block content %}{% endblock %}
    </body>
</html>

In this template I used the block control statement to define the place where the derived templates can insert themselves. Blocks are given a unique name, which derived templates can reference when they provide their content.

With the base template in place, I can now simplify index.html by making it inherit from base.html:

app/templates/index.html: Inherit from base template

{% extends "base.html" %}

{% block content %}
    <h1>Hi, {{ user.username }}!</h1>
    {% for post in posts %}
    <div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
    {% endfor %}
{% endblock %}

Since the base.html template will now take care of the general page structure, I have removed all those elements from index.html and left only the content part. The extends statement establishes the inheritance link between the two templates, so that Jinja2 knows that when it is asked to render index.html it needs to embed it inside base.html. The two templates have matching block statements with name content, and this is how Jinja2 knows how to combine the two templates into one. Now if I need to create additional pages for the application, I can create them as derived templates from the same base.html template, and that is how I can have all the pages of the application sharing the same look and feel without duplication.

Template Inheritance

106 comments

  • #51 Gaurav Gupta said 2018-10-02T14:31:56Z

    After very long time I got something meaningful.

  • #52 Miguel Grinberg said 2018-10-02T21:33:15Z

    @Aalamgeer: you need to look at the error message and stack trace in your terminal, that's the only way to determine what the problem is.

  • #53 AR said 2018-11-09T15:34:39Z

    Hi Miguel,

    Should the robots.txt file be located inside microblog foler or inside app folder or inside templates folder?

    Do we need to create a separate route to render robots.txt?

  • #54 Miguel Grinberg said 2018-11-09T17:51:47Z

    @AR: if you want Flask to server the robots.txt file then you need to create a route for it. On a production deployment you could handle this and all the other static files directly through the pubilc facing web server, which in the case of this tutorial is going to be nginx.

  • #55 Norman Dantzig said 2018-11-27T04:52:14Z

    Hey Miguel, Great tutorial. I ran through your tutorial series once. I am curious about using HAML with flask. I saw this hamlish-jinja2. Do you think it is reasonable to try with flask? Would I be able write this tutorial in HAML?

    https://github.com/Pitmairen/hamlish-jinja

  • #56 Miguel Grinberg said 2018-11-27T10:21:09Z

    @Norman: I see no problem with using HAML for this tutorial or in general for Flask applications. You should be able to translate my HTML templates into HAML.

  • #57 AR said 2018-12-23T14:21:16Z

    hi,

    this is how we we use python variable in jinja 2 -- {{ variable }} this is how we mention if statement - {% if statement %}

    how can i mention, inline if statement like - variable / constant if variable is not None else 0

    use of {{ }} or {%%} does not work.

  • #58 Miguel Grinberg said 2018-12-23T18:31:09Z

    @AR: The documentation is your friend, as always: http://jinja.pocoo.org/docs/2.10/templates/#if-expression.

  • #59 程鈺涵 said 2019-04-22T01:21:14Z

    Hi Miguel, Thank you for the kind help. I want to ask if I can render(update) a specific variable dynamically without reload page? Does any function for the need? Returning render_template needs to set all variables and cause the page reload, which is not I expected. Thank you very much! Thanks

  • #60 Miguel Grinberg said 2019-04-22T06:42:45Z

    @程鈺涵: dynamic updates to a web page need to be done in JavaScript. If you need to get data from the server, the JavaScript needs to send an asynchronous request to get the data, and then insert it in the correct place in the page.

  • #61 Sarah said 2019-04-29T22:02:53Z

    Hi there!

    I'm receiving the same error as @Claudiu. I'm using Python 3.7, Flask 1.0.2 and Jinja2 2.10.1. Thank you!

  • #62 Miguel Grinberg said 2019-04-30T11:25:33Z

    @Sarah: did you import render_template as shown above?

  • #63 mbolewar said 2019-06-14T19:56:56Z

    Really helpful for flask web applications .one question .if i wanted to launch flask using specific HOST ip and port no whats the change i need to (instead of default host ip 127.0.0.1 and port 5000)?

  • #64 Miguel Grinberg said 2019-06-15T10:20:06Z

    @mbolewar: if you want to do this in your own machine for development, see "flask --help" for all the options. If you want to do this on production, then see the production chapters of this tutorial later on.

  • #65 Nicholas said 2019-07-15T17:15:51Z

    Whenever I try to run the application after changing routes.py to

    from flask import render_template from app import app

    @app.route('/') @app.route('/index') def index(): user = {'username': 'Nicholas'} return render_template('index.html', title='Home', user=user)

    Nothing appears when I go to localhost. I am receiving these GET responses in powershell

    127.0.0.1 - - [15/Jul/2019 12:11:44] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [15/Jul/2019 12:11:50] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [15/Jul/2019 12:11:50] "GET /favicon.ico HTTP/1.1" 404 - 127.0.0.1 - - [15/Jul/2019 12:11:57] "GET /index HTTP/1.1" 200 - 127.0.0.1 - - [15/Jul/2019 12:11:57] "GET /favicon.ico HTTP/1.1" 404 -

    What is happening and what do I need to do to make it work?

  • #66 Miguel Grinberg said 2019-07-15T18:14:17Z

    @Nicholas: can you be more explicit regarding "nothing happens"? What exact URL are you connecting to from your browser? What do you see on your browser window after you enter the URL?

  • #67 Karl said 2019-09-12T12:15:31Z

    Dear Miguel,

    I've started following your tutorial and so far it's great, hats off!

    I am struggling with one tiny bit, however. I am working with PyCharm and have the project structure as you suggested, however, I don't seem to be able to import the 'app' variable in my routes.py file. If I simply include the content of the routes.py file in the init.py file, all works fine. I can't get it to work with a separate file for the routes as I'm unable to import the 'app' variable with 'import app from app'. Any suggestions?

    Thanks in advance and best regards, Karl

  • #68 Miguel Grinberg said 2019-09-12T19:48:25Z

    @Karl: the current directory for your project must be set to the microblog directory, so that the app package is in the current directory and thus can be imported as "import app" or as "from app import app".

  • #69 雷圳 said 2019-09-17T02:38:44Z

    thank you very much,I'm confused about Flask, now is clear

  • #70 Vinay S said 2019-09-24T17:38:23Z

    Is multiple and multilevel inheritance allowed in template inheritance and great tutorial Miguel Sensei

  • #71 Miguel Grinberg said 2019-09-25T17:58:10Z

    @Vinay: Yes, you can have multiple templates forming a chain of inheritance.

  • #72 Kaunda said 2019-10-01T09:37:23Z

    From Wamfie, far away Africa.Ghana.BogoRegion.DormaaEastDistrict. I only want you to know that your impact is felt even at the far end of the World.

  • #73 Oz Locke said 2019-10-11T15:42:34Z

    I'm getting a NameError on render_template. I Googled it and apparently render_template is no longer bundled with Flask, so I needed to add it in the import:

    from flask import Flask, render_template

    But I'm still getting the error:

    return render_template('index.html', title='Home', user=user) NameError: name 'render_template' is not defined

  • #74 Miguel Grinberg said 2019-10-14T09:08:29Z

    @Oz: where did you see that render_template is not part of Flask anymore? This is wrong, nothing has changed.

    Are you adding the import in the same file where you are using it? I suspect this is a misunderstanding on your part on how imports work.

  • #75 Enzo said 2019-10-24T02:49:40Z

    Awesome article, very helpful!

Leave a Comment