This tutorial is out of date! Try my longer, updated Flask-SQLite webapp tutorial here

Adding layouts to our Flask webapp

Need to share a header with every single page? Want to protect your hard work with an intimidating copyright footer on every page? Layouts are for you!

There are two simple steps to making a layout work (or: see the Flask documentation tutorial).

Step 1. Make your layout

The layout itself is the “outside” bits, the parts that stay the same on every page. Maybe the <head> section with the page title and stylesheet links, any footers, stuff like that.

Here’s a simple one, we’ll call it layout.html.

layout.html

<!doctype html>
<html>
  <head>
    <title>New York City Schools</title>
  </head>
  <body>
    <p><strong>Navigation:</strong> <a href="/">Home</a> <a href="mailto:contact@example.com">Contact me</a></p>
    {% block content %}{% endblock %}
    <p>&copy; 2015 Incredible Schools Site LLC</p>
  </body>
</html>

This page will have “New York City Schools” as the title for every page, along with some painfully simple navigation and a footer.

Pay attention to the block content/endblock section! That’s where the content from your page is going to go.

Now you need to edit your existing template to use the layout.

Step 2. Use your layout

There are two parts to using your layout:

  1. Use extends: add a line at the top of our template to instruct the page to use our layout.
  2. Adding block content: to tell the layout what exact the “content” area is.

Let’s say our initial webpage looked like this:

show.html (pre-layout)

<h1>{{ school.school_name }}</h1>
<p>This school has {{ school.total_students }} total students.</p>

First we want to tell the template to go look at layout.html, then we want to take all of our content and wrap is in block content. The changes will look like this:

show.html (post-layout)

{% extends "layout.html" %}
{% block content %}
<h1>{{ school.school_name }}</h1>
<p>This school has {{ school.total_students }} total students.</p>
{% endblock %}

Pretty easy, right?

Step 3. Party down

And now titles and navigation should be working on every page! Pretty cool, ‘eh?

If you’d like to take your layouts to the next level, try out easily styling our webapp.

Want to hear when I release new things?
My infrequent and sporadic newsletter can help with that.