Django Template Inheritance (extends, block) Tutorial 🎯

beginner
14 min

Django Template Inheritance (extends, block) Tutorial 🎯

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Django Template Inheritance. This powerful feature allows us to reuse common HTML layouts across multiple templates, saving time and promoting consistency in our projects. Let's get started!

Understanding Template Inheritance πŸ“

In Django, template inheritance allows a child template to inherit properties from a parent template. The parent template defines the common structure, and the child template adds specific content to it.

markdown
# Base Template (parent) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Default Title{% endblock %}</title> </head> <body> <header> <h1>Welcome to CodeYourCraft</h1> </header> <main> {% block content %} {% endblock %} </main> <footer> <p>Β© 2023 CodeYourCraft</p> </footer> </body> </html>
markdown
# Child Template (extends parent) {% extends "base_template.html" %} {% block title %}My Amazing Page{% endblock %} {% block content %} <article> <h2>Welcome to My Page</h2> <p>This is a child template demonstrating inheritance.</p> </article> {% endblock %}

πŸ’‘ Pro Tip: In the child template, {% extends "base_template.html" %} tells Django to use the specified parent template.

Blocks and Overriding Content πŸ“

In the base template, we define blocks where the child template can provide its unique content. In our example, we have a block for the title and the main content.

To override the content of a block in the child template, simply replace the existing block content with your own content, as shown in the child template example above.

Advanced Example: Navigation and User Authentication πŸ’‘

Let's enhance our base template with a navigation menu and user authentication links.

markdown
# Base Template (parent) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Default Title{% endblock %}</title> </head> <body> <header> <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'about' %}">About</a></li> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'login' %}">Login</a></li> {% endif %} </ul> </nav> <h1>Welcome to CodeYourCraft</h1> </header> <main> {% block content %} {% endblock %} </main> <footer> <p>Β© 2023 CodeYourCraft</p> </footer> </body> </html>

Quiz πŸ’‘

Stay tuned for our next lesson on Django Forms and Views! πŸš€