DEV Community

Cover image for jinja super blocks

Posted on

jinja super blocks

In Jinja, the template engine of Flask web framework (what is Flask?), you can create templates. You can use these templates to improve the user experience and pass Python data to the web browser.

But with a large app, you'd have to rewrite the same template over and over to get the same design?

Not exactly, there is a trick you can use to prevent you from repeating the same template code over and over.


Before playing with Flask, you should know the basics of Python. If you don't know how to use templates yet, see this post

Super blocks

So you want to add a design for all pages in your app?

Instead of copying and pasting the same code throughout all your files, you can use a super block.

There is an easier way, instead you can use a super block.

{{ super() }}

We'll create a new file called layout.html in the directory templates. This is not a plain html file, but a jinja template. This is the contents of the file,

<!DOCTYPE html>
    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="" rel="stylesheet" media="screen">
    <style type="text/css">
      .container {
        max-width: 500px;
        padding-top: 100px;
      h2 {color: red;}
    <div class="container">
      <h2>My App</h2>
      {% block content %}{% endblock %}
      <div class="footer">
        {% block footer %}
          The footer of the page
        {% endblock %}

Key here is the user of {% block content %} and {% block footer %}, which will inject your pages.

Then change template.html to have the surrounding tags:

{% extends "layout.html" %}
{% block content %}
<p>String a is {{a}}</p>
<p>Loop through variable b</p>
{% for x in b %}
{% endfor %}
{% endblock %}

It then surrounds your page with the design:

flask use of layout

Start the server and open the url

$ python3
 * Serving Flask app "example" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 251-419-329

You can now apply this template to any URL route in your Flask app!

Related links:

Top comments (0)