Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a standard, static variable from all views in Django?

Tags:

django

I'm working on a blog application, and I want to have a sidebar that includes a list of all the months the blog has been in existence, to provide links to archives pages. Moreover, I'd like to make this automatically update when the month changes, rather than hardcoding it in the template. Of course, as far as I can tell, this means that I'll have to calculate the list of months in every view, and pass it into every template from every view.

I'd like to avoid this, if possible. Is there a way to calculate the list once and automatically apply it to every template, without having to explicitly pass it into the template from every view?

like image 442
mipadi Avatar asked Feb 23 '09 01:02

mipadi


2 Answers

There are a few possible solutions to your problem.

If you really want to have this on every page on your site a context processor is probably your best choice. Context processors are basic way to inject data into all template contexts. Be aware however that the context processor will be called on every request.

An alternative solution would be to create a custom template tag and use it on a shared base template for all of the pages you wish to have your sidebar. Template tags are a bit more complex to create but they are more flexible.

With either solution you should also look at Django's cache framework. The cache framework makes it pretty easy to temporarily store your calculated values for a while to save some work on each request.

like image 185
SeanOC Avatar answered Oct 16 '22 10:10

SeanOC


You want a template context processor

Django - having middleware communicate with views/templates

http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#id1

like image 38
S.Lott Avatar answered Oct 16 '22 12:10

S.Lott