Search code examples
djangohtmlheadtemplate-inheritance

Proper method for Django template inheritance of <head> content


I have a base.html template with sitewide tags for charset, google-site-verification, stylesheets, js.... I also need to set up blocks for page specific title tags and meta descriptions.

I am wondering, should I set up a {% block head %} in my base.html and in my inherited template mix tags in that block, or should i set up specific blocks such as {% block meta %} and {% block title %} so that the tags appear in their proper places when Django renders to html.

Does this make sense? If I view source with all the tags mixed in one {%block head %} things are a bit out of order, but if I add specific blocks for each tag they are in order but use much more code...?


Solution

  • I normally have three blocks. Those three have covered all my and my colleague's needs in the last 1.5 year :-)

    • A block for css.

    • A block for javascript.

    • A block called "head-extras". Often you want to do something special on a page-by-page basis like adding a link element that points at your rss feed. Or some inline javascript snippet. With this block, you allow these corner cases in a clear way.

    In templates that extend the base template, you can use {{ super }} in the css and javascript blocks to get the "parent's" list and extend it with your own.

    I also have a head block around the whole thing for those few cases where you just want to override everything in the head :-)