Proper method for Django template inheritance of <head> content
Asked Answered
H

1

7

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...?

Haimes answered 13/12, 2011 at 22:51 Comment(1)
i guess it depends on what you typically think you'll need to override in other templates.Gilgai
F
6

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 :-)

Fishing answered 13/12, 2011 at 23:5 Comment(3)
I suppose its a toss-up between excessive template blocks or jumbled head tags - is there any reason to prefer one over the other?Haimes
The order isn't too important. It is for my css and javascript, though, as I wrap them in a django-compressor tag to combine them on the fly into one file. Apart from that technical reason, I'd just keep the number of blocks non-excessive. The browser doesn't mind the order of head tags, but you yourself profit a lot from template neatness.Fishing
Thanks for your time Reinout, and thank you for mentioning {{ super }} and django-compressor - I will be investigatingHaimes

© 2022 - 2024 — McMap. All rights reserved.