Fixed #29336 -- Doc'd circular template inheritance

This commit is contained in:
David Smith 2020-06-23 06:57:19 +01:00 committed by Carlton Gibson
parent e70dc506d7
commit 2c2f4b3799
2 changed files with 47 additions and 0 deletions

View File

@ -97,3 +97,43 @@ then your directory structure will look like:
With :setting:`APP_DIRS<TEMPLATES-APP_DIRS>` set to ``True``, the template
loader will look in the app's templates directory and find the templates.
.. _extending_an_overridden_template:
Extending an overridden template
================================
With your template loaders configured, you can extend a template using the
:ttag:`{% extends %}<extends>` template tag whilst at the same time overriding
it. This can allow you to make small customizations without needing to
reimplement the entire template.
For example, you can use this technique to add a custom logo to the
``admin/base_site.html`` template:
.. code-block:: html+django
:caption: templates/admin/base_site.html
{% extends "admin/base_site.html" %}
{% block branding %}
<img src="link/to/logo.png" alt="logo">
{{ block.super }}
{% endblock %}
Key points to note:
* The example creates a file at ``templates/admin/base_site.html`` that uses
the configured project-level ``templates`` directory to override
``admin/base_site.html``.
* The new template extends ``admin/base_site.html``, which is the same template
as is being overridden.
* The template replaces just the ``branding`` block, adding a custom logo, and
using ``block.super`` to retain the prior content.
* The rest of the template is inherited unchanged from
``admin/base_site.html``.
This technique works because the template loader does not consider the already
loaded override template (at ``templates/admin/base_site.html``) when
resolving the ``extends`` tag. Combined with ``block.super`` it is a powerful
technique to make small customizations.

View File

@ -407,6 +407,13 @@ Here are some tips for working with inheritance:
not be automatically escaped (see the `next section`_), since it was
already escaped, if necessary, in the parent template.
* By using the same template name as you are inheriting from,
:ttag:`{% extends %}<extends>` can be used to inherit a template at the same
time as overriding it. Combined with ``{{ block.super }}``, this can be a
powerful way to make small customizations. See
:ref:`extending_an_overridden_template` in the *Overriding templates* How-to
for a full example.
* Variables created outside of a :ttag:`{% block %}<block>` using the template
tag ``as`` syntax can't be used inside the block. For example, this template
doesn't render anything::