How to Use extends in Jinja2 Templates with Flask
In Flask, use the
{% extends 'base.html' %} statement in a Jinja2 template to inherit from a base template. This lets you reuse common HTML structure and override specific blocks for each page.Syntax
The {% extends 'base.html' %} statement tells Jinja2 that this template inherits from base.html. You place it at the top of your child template. Inside the base template, you define {% block block_name %}{% endblock %} sections that child templates can override.
This helps keep your HTML DRY (Don't Repeat Yourself) by sharing common layout code.
jinja2
{% extends 'base.html' %}
{% block content %}
<!-- Child template content here -->
{% endblock %}Example
This example shows a base template with a header and a content block, and a child template that extends it and fills the content block.
python/jinja2
# app.py from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('child.html') if __name__ == '__main__': app.run(debug=True) # templates/base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Site</title> </head> <body> <header> <h1>Welcome to My Site</h1> </header> <main> {% block content %}{% endblock %} </main> </body> </html> # templates/child.html {% extends 'base.html' %} {% block content %} <p>This is the home page content.</p> {% endblock %}
Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Site</title>
</head>
<body>
<header>
<h1>Welcome to My Site</h1>
</header>
<main>
<p>This is the home page content.</p>
</main>
</body>
</html>
Common Pitfalls
- Forgetting to place
{% extends %}at the very top of the child template causes errors. - Not defining matching
{% block %}names in the base template means child content won't show. - Using relative paths incorrectly in
{% extends %}can cause template not found errors; always use the correct template folder path.
jinja2
{# Wrong: extends not at top #}
<p>Intro text</p>
{% extends 'base.html' %}
{# Right: extends at top #}
{% extends 'base.html' %}
<p>Intro text</p>Quick Reference
{% extends 'base.html' %}: Inherit from base template.{% block name %}{% endblock %}: Define replaceable sections.- Child templates override blocks to customize content.
- Always put
{% extends %}at the top of child templates.
Key Takeaways
Use {% extends 'base.html' %} at the top of your child templates to inherit layout.
Define blocks in the base template that child templates can override with {% block %}.
Always place the extends statement before any other content in the child template.
Extends helps keep your HTML clean by reusing common page structure.
Check template paths carefully to avoid 'template not found' errors.