Version 7 (modified by L.Plant.98@…, 13 years ago) (diff)


Template pitfalls

Here's how to dodge some of the more obvious template pitfalls:


Not a pitfall, but a tip:

Use {% debug %} in a template block if you want to know what is defined and can be used in a template.

The debug output is pretty ugly unless you look at it through View Source, or you can do it this way:

{% filter linebreaks %}
  {% debug %}
{% endfilter %}

or more simply:

  {% debug %}

custom context variables for generic views

More advanced versions of the base template (mine is base.html, following the model set in the administration interface) might need a consistent set of context variables generated on the fly based on the identity of the current user, what they're doing, what's happening elsewhere on the site, and so on.

If you're using generic views, though, there's no obvious way to make these context variables available.

The solution is to use custom template tags, which can modify a page's context variables on the fly.

If your needs are middling simple, or you don't want to have to write your own custom template tag from scratch, I've developed a generic option: vars, which defines a fairly generic pushvars tag that calls the function of your choice and pushes its results into the current context.

I'm posting this to atone for my previous crummy advice on this Wiki page.

- garthk

But what if your custom template tags needs access to the HttpRequest object in order to do it's stuff? For example, if you have a menu or a breadcrumb that depends on request.path, or on the session etc? Does the DjangoContext object provide access to this in any way? The only ways I've found are things like subclassing DjangoContext and getting that to use the request to create any data needed for the base templates/custom template tags, but that won't work with generic views AFAIK. (I'm happy using my current method, as I haven't actually used generic views yet, but imagine I may need to soon). Cheers.

Back to Top