Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Overriding AND extending an app template

If you want to override a template coming with an app in django (in app/templates/app/) you create a template of the same name in another directory, which the template loader checks before the app's template dir. If you just want to override certain blocks of the template you also have to copy the whole template and change that block, which is actually not very DRY.

Does anybody know a way to override the orginial template, while at the same moment extending it, so that you just have to override the specific block you want to change? (the thing is doing this without changing the template's name, because in some cases you might have to change the view to make it work with another template)

EDIT: As Adam Taylor pointed out in the comments from Django 1.9 on this is possible without any hacks.

like image 248
Bernhard Vallant Avatar asked Oct 19 '10 11:10

Bernhard Vallant


People also ask

How do I override a Django template?

To do so, you will have to change the project's settings.py . Find the TEMPLATES section and modify accordingly. To override the default template you first need to access the template you want to modify from the django/contrib/admin/templates/admin directory.

Can you extend more than one template Django?

Use Django extends in multiple templates html to multiple HTML documents using the same document structure and DTL block content tags. This means the header can render in multiple templates.

What is difference between extend and include in Django?

Extends sort of 'includes' the parent template and then can overwrite parts of it for different functionality. Include does a simple include rendering a template in a current context.

What does {% include %} do in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.


1 Answers

I think the answer from this related question is pertinent; currently, the best solution seems to be to use a custom template loader from the django-apptemplates package on PyPI, so you can just use pip to install it (e.g. pip install django-apptemplates).

The template loader allows you to extend a template in a specific app; for example, to extend the index page of the admin inteface, you would add

'apptemplates.Loader', 

to your TEMPLATE_LOADERS list in settings.py, and use

{% extends "admin:admin/index.html" %} 

in your templates.

like image 99
leech Avatar answered Sep 21 '22 05:09

leech