Jinja extend template layout block


We use extend to connect between templates. We use block both to mark the area that will be replaced and the content that will replace it.

examples/flask/template-extends/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-extends/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>Main page</title>' in rv.data, 'title'
    assert b'This is the content' in rv.data, 'content'

examples/flask/template-extends/templates/index.html
{% extends 'layouts/base.html' %}

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

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

examples/flask/template-extends/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>{% block title %}{% endblock %}</title>
</head>
<body>
<a href="/">Home</a>
<hr>

{% block content %}{% endblock %}

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