Don
Don

Reputation: 17606

Django: extend overridden template

I have two applications in my settings.INSTALLED_APPS:

INSTALLED_APPS = [
    'application2',
    'application1'
]

and want application2 to change a template from application1 (e.g. by adding a button).

How can achieve this without overriding the whole template?

NOTE

The problem is that the two templates have the same name ("mytemplate.html") and the same folder name ("application1"):

\project_root
    \application1\templates\application1\mytemplate.html
    \application2\templates\application1\mytemplate.html

so that I cannot write:

{% extends "application1\mytemplate.html" %}

because both templates are named "application1\mytemplate.html".

Upvotes: 4

Views: 316

Answers (3)

m000
m000

Reputation: 6077

I don't think this is possible for the case you describe because it implies that INSTALLED_APPS order matters. As it is stated in the django book:

The order of INSTALLED_APPS doesn’t matter, but we like to keep things alphabetical so it’s easy for a human to read.

I understand that this is not the official documentation. However the book is authored by Adrian Holovaty and Jacob Kaplan-Moss (the Django creators), so I'll take their word on it.

But if you think a bit about it you will see why ordering is not such a great idea: It only helps in specific - easy cases. In slightly more complex cases it wouldn't help. E.g.:

  • You have app1, app2, app3.
  • Both app2 and app3 extend/override templates app1/a.html and app1/b.html.
  • You want to use a.html as defined in app2 and b.html as defined in app3.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599450

Templates aren't really owned by applications. They can be grouped into application directories if you like, but are pretty much independent of them.

The way to override part of a template, whatever application provided it, is to inherit from it using {% extends 'template_name.html' %} and then define whatever blocks you need to override. Of course, this means that the parent template will need to have those blocks already defined - otherwise you'll need to override the smallest relevant block that is defined, and repeat some of the content around the bit you need to change.

Upvotes: 1

Andrew Kurinnyi
Andrew Kurinnyi

Reputation: 767

I don't think it is possible, unless you have different template names, then you can use {{ block.super }}

Once loader finds correct file, it doesn't look any further, so you don't have an access to overridden template in your new template.

https://code.djangoproject.com/browser/django/trunk/django/template/loaders/app_directories.py#L57

Upvotes: 1

Related Questions