Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Jinja template inheritance - super

  • super

  • Using the super() call we can inherit the content of the block

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/page")
def page():
    return render_template('page.html')
import app


def test_app():
    web = app.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert b'<a href="https://code-maven.com/">Code Maven</a>' in rv.data, 'footer'
    assert b'<title>Demo: Main page</title>' in rv.data, 'main title'
    assert b'This is the content' in rv.data, 'main page content'
    assert b'original' not in rv.data, 'no inherited content'

def test_page():
    web = app.app.test_client()

    rv = web.get('/page')
    assert rv.status == '200 OK'
    assert b'<a href="https://code-maven.com/">Code Maven</a>' in rv.data, 'footer'
    assert b'<title>Demo: Other page</title>' in rv.data, 'page title'
    assert b'The original content' in rv.data, 'page content'
    assert b'This is the content' in rv.data, 'inherited content'

{% extends 'layouts/base.html' %}

{% block title -%}
Main page
{%- endblock %}

{% block content %}
This is the content
{% endblock %}

{% extends 'layouts/base.html' %}

{% block title -%}
Other page
{%- endblock %}

{% block content %}
{{ super() }}
This is the content
{% endblock %}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
  <title>Demo: {% block title %}{% endblock %}</title>
</head>
<body>
<a href="/">Home</a>
<hr>

{% block content %}
The original content
{% endblock %}

<hr>
<a href="https://code-maven.com/">Code Maven</a>
</body>
</html>