Flask Template Inheritance
Template inheritance shares one layout across many pages. A child template fills the blocks of a parent.
Write the two template files
This code writes the parent and the child into the templates folder. The child extends the parent and fills the body block.
import os
os.makedirs("templates", exist_ok=True)
with open("templates/base.html", "w") as f:
f.write("<h1>My Site</h1>{% block body %}{% endblock %}")
with open("templates/child.html", "w") as f:
f.write('{% extends "base.html" %}{% block body %}<p>Hello page</p>{% endblock %}')Render the child
The view loads child.html with render_template. Flask loads the parent, then fills the body block with the child HTML.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/page")
def page():
return render_template("child.html")Ask for the page
The test client asks for /page and prints the parent layout with the child block filled in.
client = app.test_client()
print(client.get("/page").data.decode())Example
import os
os.makedirs("templates", exist_ok=True)
with open("templates/base.html", "w") as f:
f.write("<h1>My Site</h1>{% block body %}{% endblock %}")
with open("templates/child.html", "w") as f:
f.write('{% extends "base.html" %}{% block body %}<p>Hello page</p>{% endblock %}')
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/page")
def page():
return render_template("child.html")
client = app.test_client()
print(client.get("/page").data.decode())Key points
- The parent holds the shared HTML and {% block %} marks.
- The child names the parent with {% extends %}.
- The child fills each block with its own HTML.
- render_template("child.html") loads the child file by name.
- One layout serves every page of the site.
In this example, the parent and child templates are written into the templates folder first. The parent holds the heading and the body block. The child extends the parent and fills the block. The view renders the child, and the test client prints the joined page.
Note
Block names must match between parent and child.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does {% extends "base.html" %} do in a child template?