When you render a template with a given context, every key in the context dictionary becomes a variable in the template that you can access and use. Every time you render a template, you give it a “context” this is a dictionary-like object whose keys are variable names and whose values are the values of the variables. But having to call that in every single template will probably get a bit cumbersome and feels like it violates the DRY principle wouldn’t it be nice if Django provided an easier way to do this?Įnter RequestContext and context processorsĪs it turns out, Django provides an extremely easy way to do this. So you’d write a simple tag which imports your settings file and returns the value of the MEDIA_URL setting into the template context you could maybe call it get_media_url. Django lets you specify where your media files come from via the MEDIA_URL setting. You could write a template tag to populate that variable, and it’d be extremely easy to do with a convenience function Django provides: the simple_tag decorator, which lets you omit a lot of the boilerplate of writing a template tag when all you want is to spit out some value into the template.Ī recent example that came up on the django-users mailing list was a template tag to retrieve the base URL for your media (typically you want to store “media” like images, stylesheets and JavaScript in a particular location on your server, or possibly even have a separate server for them if you’re using Apache and mod_python - incurring the overhead of mod_python on a request which will just serve up a file from disk wastes resources). Last time around we looked at how to write an effective template tag, with the focus on writing a flexible template tag that would make it easy to pull in various types of recent content in any page I use a tag similar to the one in that entry to pull out the recent entries, links and comments in the footer of every page on this site.įor situations where you want to get content out of your database, a template tag is typically the best way to go, but consider a related situation: what happens when you want a particular variable - not a content object - to be available in the context of every template?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |