- super
Jinja template inheritance - super
- Using the super() call we can inherit the content of the block
examples/flask/template-inheritance/app.py
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')
examples/flask/template-inheritance/test_app.py
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'
examples/flask/template-inheritance/templates/index.html
{% extends 'layouts/base.html' %} {% block title -%} Main page {%- endblock %} {% block content %} This is the content {% endblock %}
examples/flask/template-inheritance/templates/page.html
{% extends 'layouts/base.html' %} {% block title -%} Other page {%- endblock %} {% block content %} {{ super() }} This is the content {% endblock %}
examples/flask/template-inheritance/templates/layouts/base.html
<!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>