Django: overriding template extension

I have two applications in my settings. INSTALLED_APPS:

INSTALLED_APPS = [ 'application2', 'application1' ] 

and you want application2 to change the template from application 1 (for example, by adding a button).

How to achieve this without overriding the entire 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 can not write:

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

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

+4
source share
3 answers

I do not think that this is possible for the case you are describing, because it means that the order of INSTALLED_APPS matters. As stated in the django book :

The INSTALLED_APPS order does not matter , but we love to keep things in alphabetical order so that they are easy for people to read.

I understand that this is not official documentation. However, the book was written by Adrian Holovati and Jacob Kaplan-Mos (creators of Django), so I will speak it.

But if you think a little about it, you will understand why ordering is not such a great idea: It helps only in special cases. In somewhat more complex cases, this would not help. For instance:.

  • You have app1 , app2 , app3 .
  • Both app2 and app3 extend / redefine the app1/a.html and app1/b.html .
  • You want to use a.html as defined in app2 and b.html as defined in app3 .
+2
source

I do not think this is possible, if you do not have different template names, you can use {{block.super}}

Once the bootloader finds the correct file, it no longer looks, so you do not have access to the overridden template in the new template.

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

+1
source

Templates are not really application related. They can be grouped into application directories if you wish, but are largely independent of them.

The way to override part of a template, no matter what application it provides, is to inherit it with {% extends 'template_name.html' %} and then define all the blocks that need to be redefined. Of course, this means that the parent template will have to have blocks already defined - otherwise you will need to redefine the smallest matching block that is defined and repeat the part of the content around the bit that you need to change.

+1
source

Source: https://habr.com/ru/post/1395380/


All Articles