Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Template Inheritance System | Templates
Django: Build Your First Website

book
Template Inheritance System

In Django, template inheritance is a mechanism that allows you to create base templates and then extend or override them in derived templates. This helps to avoid code duplication and makes maintenance easier.

The basic working principle of template inheritance in Django:

Create a Base Template: Firstly, you create a base template that contains common elements shared across your entire web page. This could include a header, navigation, footer, and other elements.

html

base.html

copy
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<div id="header">
<!-- Site header -->
<h1>My Site</h1>
</div>
<div id="content">
<!-- Main content of the page will be inserted here -->
{% block content %}{% endblock %}
</div>
<div id="footer">
<!-- Site footer -->
<p>&copy; 2023 My Site</p>
</div>
</body>
</html>

Create a Derived Template: Next, you create a derived template that extends the base template and provides specific content for its page. I'll name this template notes.

html

notes.html

copy
<!-- notes.html -->
{% extends 'base.html' %}

{% block title %}My Special Page{% endblock %}

{% block content %}
<h2>Welcome to my special page!</h2>
<p>This is the content of my special page.</p>
{% endblock %}

In this example, {% extends 'base.html' %} indicates that this template extends the base template. The {% block ... %}{% endblock %} tags define areas where content can be overridden in derived templates.

Render the Template in Django Views: In Django views, you specify which template to use for rendering a particular page.

from django.shortcuts import render

def special_page(request):
return render(request, 'notes.html')

In this case, the render(request, 'notes.html') call tells Django to use the 'notes.html' template for displaying the page.

After these steps, when a visitor accesses the page, Django automatically combines the base and derived templates, inserting the content of blocks from the derived template into the corresponding blocks in the base template. This makes it easy to manage the common appearance and structure of web pages in your Django project.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 2
some-alt