Saturday, October 1, 2011

Re: View decorator for common navigation elements?

This post is particularly well timed, since I have the exact same
question. I'm excited to say the company has, after many years, been
convinced to stop working on our internal PHP framework and we chose
django as its replacement (in sad news, I was the main dev on that
framework, and poured my heart and many long nights into it. but it's
PHP code, so good riddance)

One nifty thing it could do was "auto-prepare" elements on a page,
much in the style of "pull-style" frameworks that call hooks/callbacks
based on the *view*, rather than "pushing" data onto the page. our
framework supported both styles, but django seems to be distinctly
"push" based. So I miss being able to just add an
"autoprepareTopNav()" method to a parent controller class, and have it
automatically called whenever the top-nav element was outputted.

BUT, the "common elements" problem strikes me as one of those
"certainly this has been done before" problems, and I would love to
know what the accepted django-ic solution is. My coworker, who is
more versed in django & python, wrote a context processor to fetch top-
nav and footer pages. But since it's a CP, it gets called on *every*
page, not just those that need it. _I'd_ rather it not execute except
on those pages that explicitly need that data.

I played with a view-decorator pattern that had view methods returning
*either* a response object or a (template, dict) tuple that could be
passed up the chain to include other view-method-like-decorators, and
they would add their data — in much the same way that Victor describes
here.

The benefit to that approach is that if you have *multiple* elements
that use *a common set* of data (for instance, on a site I'm working
on now we've got a category dropdown that appears in multiple places -
the top nav search, a search callout, and on the search results
page). I should not fetch this category list multiple times, and
template tags would not alleviate that, unless I throw in some global
mechanism where I can look for the data. Are class-based views the
logical solution?

Okay, so, a question does emerge. I think template tags are the right
answer here. How do I write three template tags that all use a common
set of data?


On Sep 30, 3:47 pm, Victor Hooi <victorh...@gmail.com> wrote:
> heya,
>
> I do like the idea of just including a custom template tag =).
>
> Hmm, can custom template tags interact with models or query the database
> like that?
>
> Firstly, Is it possible, and secondly, is it considered good practice?
>
> Cheers,
> Victor

--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment