Template Inheritance
Template inheritance is one of Jinja2’s most powerful features. It allows you to build a base “skeleton” template that contains common elements of your site and defines blocks that child templates can override.Why Use Template Inheritance?
- Reduce duplication: Write common HTML once in a base template
- Maintain consistency: Ensure all pages share the same structure
- Easy updates: Change the layout in one place
- Better organization: Separate layout from content
Basic Inheritance with extends
Child templates use{% extends %} to inherit from a parent template.
Base Template
Create a base template with the common structure:Child Template
Child templates extend the base and fill in the blocks:Defining Blocks
Blocks are placeholders in the base template that child templates can override.Defining Blocks
Overriding Blocks
Block Best Practices
- Name blocks descriptively:
content,title,stylesheets,scripts - Provide defaults when appropriate: Default titles, empty script blocks
- Keep blocks focused: Each block should have a single purpose
- Document block purposes: Comment what each block is for
Common Block Patterns
Title Block
Content Block
Stylesheet Block
Script Block
Multi-Level Inheritance
You can have multiple levels of inheritance:Using super()
Thesuper() function lets you render the parent block’s content:
Include Directives
Use{% include %} to insert reusable template fragments:
Creating Partials
Including Partials
Include with Variables
Conditional Includes
Common Template Patterns
Two-Column Layout
Form Layout
Error Page Layout
Complete Example
Base Template
Child Template
Next Steps
- Learn about template functions
- Explore asset handling
- Read the template overview