Friday, October 17, 2008

Template inheritance in Django

I've just discovered a killer feature of Django... template inheritance, using the {% block %} and {% extends %} tags.

It's probably there in other templating systems and frameworks so I'm probably coming late to the party but for someone who is more than a bit obsessive about nice clean structures in website development, avoidance of repetition in code, etc. it really appeals to me, more than all the other nifty things I've seen that Django can do.

To quote from the Django documentation:

One common way of using inheritance is the following three-level approach:
  • Create a base.html template that holds the main look-and-feel of your site.
  • Create a base_SECTIONNAME.html template for each "section" of your site. For example, base_news.html, base_sports.html. These templates all extend base.html and include section-specific styles/design.
  • Create individual templates for each type of page, such as a news article or blog entry. These templates extend the appropriate section template.

No comments: