On Mon, 2009-03-02 at 05:00 -0800, Daniel Roseman wrote:
> On Mar 2, 10:41 am, Mattias <lin...@gmail.com> wrote:
> > Hi,
> >
> > I'm just learning Django, and had a question with my first site.
> >
> > To have a common layout for multiple pages (even those in different
> > applications / python code folders) on the site, I'm using template
> > inheritance.
> > But the base template uses a few variables, for example the name of
> > the logged in user and some of his settings. These need to be provided
> > as parameters from *every* view's render_to_response call that uses a
> > template inheriting from base.
> >
> > How should I structure my code to access these in every view?
> > An idea I had was to:
> > * make a basehelper.py to go with the base.html template
> > * have a get_params(request) function there that returns a dict with
> > the base template parameters
> > * every view would use this and add its own values before passing it
> > to render_to_response.
> >
> > But is there something more generic for this problem in Django?
> >
> > Mattias
> 
> This is what context processors are for - they insert variables into
> the template context. See
> http://docs.djangoproject.com/en/dev/ref/templates/api/#id1

Well, context processors are sometimes useful here. One restriction,
though, is that context processors are only given the "request" as a
parameter, not everything else that is passed to the view function.

Sometimes, if extra information is needed, it's more useful to go with a
common "finishing up" function that you call. Since a view typically
ends with a call to render_to_response(), you aren't adding any extra
complexity if you replace that with a call to
finish_up_view(request, ...), passing in a whole bunch of information.

The finish_up_view() function, which you write, can then add in whatever
extra information you like to the context -- which can now depend on
more than just the "request" variable -- and finally return the result
of render_to_response().

I find myself using that pattern almost routinely nowadays. Even if
finish_up_view() is initially only just a proxy for
render_to_response(), over time, more things tend to be added as a
common "do common extra stuff" holder.

Again, context processors might well do the necessary stuff, but they
aren't always powerful enough or at the right place in the code path. So
this is another idea to keep in mind.

Regards,
Malcolm



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to