0
0
DjangoHow-ToBeginner · 3 min read

How to Use Block in Django Template: Syntax and Examples

In Django templates, use the {% block block_name %}{% endblock %} tags to define sections that child templates can override. This allows you to create a base template with placeholders that other templates can fill or replace.
📐

Syntax

The {% block %} tag defines a named section in a Django template. It starts with {% block block_name %} and ends with {% endblock %}. The block_name is an identifier for the section.

Child templates can override these blocks to customize content while reusing the base layout.

django
{% block block_name %}
  <!-- Content goes here -->
{% endblock %}
💻

Example

This example shows a base template defining a content block and a child template overriding it.

django
{# base.html #}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
  <header>
    <h1>Welcome to My Site</h1>
  </header>
  <main>
    {% block content %}
    <p>This is the default content.</p>
    {% endblock %}
  </main>
  <footer>
    <p>Footer info here.</p>
  </footer>
</body>
</html>

{# child.html #}
{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
  <p>This is the overridden content in the child template.</p>
{% endblock %}
Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <header> <h1>Welcome to My Site</h1> </header> <main> <p>This is the overridden content in the child template.</p> </main> <footer> <p>Footer info here.</p> </footer> </body> </html>
⚠️

Common Pitfalls

  • Forgetting to use {% endblock %} causes template errors.
  • Using the same block name multiple times in one template can cause confusion.
  • Not extending the base template with {% extends "base.html" %} means blocks won’t override anything.
  • Overriding a block but not including content from the base block if needed (use {{ block.super }} to include base content).
django
{# Wrong: missing endblock #}
{% block content %}
<p>Content without endblock causes error</p>

{# Right: with endblock #}
{% block content %}
<p>Proper content.</p>
{% endblock %}
📊

Quick Reference

Block Tag Cheat Sheet:

TagPurpose
{% block block_name %}...{% endblock %}Defines a named section to override in child templates
{% extends "base.html" %}Inherits from a base template to enable block overrides
{{ block.super }}Includes content from the parent block inside an override

Key Takeaways

Use {% block %} and {% endblock %} to define overridable sections in templates.
Child templates override blocks by using the same block name inside {% block %} tags.
Always close blocks with {% endblock %} to avoid template errors.
Use {% extends %} in child templates to inherit and override blocks from a base template.
Use {{ block.super }} inside a block to include the parent block’s content.