Template Inheritance (Django)

Template inheritance lets Django templates share a common layout. A base template defines the page skeleton with {% block %} placeholders, and child templates use {% extends %} to fill in only the blocks they need to change.

Django

Inheritance is the DRY (don't repeat yourself) tool for templates. You write base.html once with the header, footer, and {% block content %}{% endblock %} placeholders, then every page {% extends 'base.html' %} and overrides just the blocks it cares about.

Inside an overriding block you can call {{ block.super }} to include the parent's content as well as your own. Blocks can be nested and a child can extend a template that itself extends another, building multi-level layouts.

{% extends %} must be the first tag in a child template, and anything outside a block in a child is ignored — only block contents are substituted into the parent.

Syntax

{% extends "base.html" %}
{% block content %}...{% endblock %}

Examples

Python

<!-- base.html -->
<html><body>
  <header>My Site</header>
  {% block content %}{% endblock %}
</body></html>

<!-- home.html -->
{% extends "base.html" %}
{% block content %}<h1>Welcome</h1>{% endblock %}

Learn it in a lesson

See also

Back to the Dictionary