Changes between Initial Version and Version 1 of ExtendingTemplates


Ignore:
Timestamp:
Aug 5, 2008, 6:49:33 PM (16 years ago)
Author:
simon
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ExtendingTemplates

    v1 v1  
     1== Extending templates ==
     2
     3(Originally posted here by Simon Willison on 6th August 2008)
     4
     5Django's template inheritance mechanism allows templates to extend other templates and replace named blocks within them. See here for a full explanation: http://www.djangoproject.com/documentation/templates/#template-inheritance
     6
     7This feature becomes even more powerful when coupled with Django's template path concept, as discussed by Jeff Croft in this article: http://jeffcroft.com/blog/2008/aug/05/default-templates-django/
     8
     9A frequently requested feature is the ability to provide an over-ride template that also extends itself. Consider the following:
     10
     11{{{
     12# In settings.py
     13TEMPLATE_DIRS = ('/var/templates/default', '/var/templates/mysite')
     14
     15# In default/homepage.html
     16BIG COMPLEX TEMPLATE HERE
     17{% block stylesheets %}<link rel="stylesheet" type="text/css" href="styles.css">{% endblock %}
     18MORE BIG COMPLEX TEMPLATE HERE
     19
     20# In mysite/homepage.html
     21{% extends "homepage.html" %}
     22{% block stylesheets %}<link rel="stylesheet" type="text/css" href="mysite-styles.css">{% endblock %}
     23}}}
     24
     25In other words, we want mysite/homepage.html to reuse default/homepage.html almost entirely, only replacing the stylesheets named block.
     26
     27The above won't work - Django will throw confusing errors.
     28
     29It turns out it IS possible to get this to work, if you're willing to do some devious tricks with your TEMPLATE_DIRS setting. Consider the following:
     30
     31{{{
     32# In settings.py
     33TEMPLATE_DIRS = ('/var/templates/default', '/var/templates/mysite', '/var/templates')
     34
     35# In mysite/homepage.html
     36{% extends "default/homepage.html" %}
     37{% block stylesheets %}<link rel="stylesheet" type="text/css" href="mysite-styles.css">{% endblock %}
     38}}}
     39
     40This will do what we want it to do.
     41
     42The trick is very simple - we add a new directory right at the end of TEMPLATE_DIRS which is the parent of all of the other directories. This has the effect of making every template file within our system uniquely addressable. Most of the time we will use the normal paths, but in the special case of wanting to extend a template with an over-riding version of itself we can reference its parent's full, unambiguous template path in the extends tag.
Back to Top