views:

89

answers:

2

I've got a small snippet that I want in my sidebar. The snippet will be visible on each page, and while cheap to fetch (about 50ms on my super-slow netbook!), will change so infrequently that I'd quite like to cache it (partly because I've yet to use Django's cache framework, and I'd like to learn).

I'm not sure what the best way to go here is - middleware or a custom template tag? I'm not sure how easy it would be to implement caching with these approaches. This is such a standard thing to want to do (that is, fragment caching of a fragment visible on each page) that I'm sure there's a Djangonic way to do it, but I can't find what it is.

How do you do it?

+2  A: 

This sounds perfect for Template fragment caching.

Ned Batchelder
This is good, as long as it doesn't matter that there will be a delay once the content changes.
Fragsworth
@Fragsworth - it doesn't.
Dominic Rodger
+1 from me - thanks!
Dominic Rodger
+1  A: 

I don't think you need to use middleware. A custom template tag would work for this. Since you're doing something like a status message, it would be unrelated to whatever the current view is, so the tag is definitely appropriate.

Just set up the cache back-end (this is very easy to do) and you will have access to cache.set() and cache.get() methods which you can use to store, and retrieve your status message. Be sure to clear the cache whenever the status message is updated.

Fragsworth
+1 - I've marked this as the accepted answer, but there's nothing wrong with Ned's answer either.
Dominic Rodger