Jiri Barton wrote: > Hello there, > > I have the following problem. Here's my template fragment; it defines a > menu: > > <ul> > <li>mushrooms</li> > <li>cheese</li> > <li>tomatoes</li> > <li>onion</li> > </ul> > > Now, I'd like to be able to highlight one item in some templates, and > another item in other templates. Only the templates know what should be > highlighted. To do that, I'd like to define a class="selected" for that > item, so that the output will be for example: > > <ul> > <li>mushrooms</li> > <li>cheese</li> > <li class="selected">tomatoes</li> > <li>onion</li> > </ul> > > Now, I'd like to write the menu only once and then use it the following > way: > > {% declare menuselection tomatoes %} > {% include "menu" %} > > The menu would have been defined as follows: > > <ul> > <li {% ifequal menuselection "mushrooms" %} class="selected" {% > endifequal %}>mushrooms</li> > <li {% ifequal menuselection "tomatoes" %} class="selected" {% > endifequal %}>tomatoes</li> > <li {% ifequal menuselection "cheese" %} class="selected" {% > endifequal %}>cheese</li> > <li {% ifequal menuselection "onion" %} class="selected" {% > endifequal %}>onion/li> > </ul> > > A couple of questions: does anyone have a better idea how to do it? > And, of course, the declare tag does not exists - is there a way of > defining a variable from within a template? > > Thanks, > Jiri > >
I would do it like this (python 2.4 decorator syntax, no i18n) : in a templatetag module: (read the template docs) ----------------------- from django.core import template register = template.Library() names = ['mushrooms','cheese','tomatoes','onion'] @inclusion_tag("myapp/menu") def menu(selected): return { 'items': [ { 'name':name, 'selected': name == selected } for name in ] } ----------------------- myapp/menu.html: ----------------------- <ul> {%for item in items%} <li {%if item.selected%}class='selected'{%endif%} > {%endfor%} </ul> ---------------------- Obviously you could adjust this fairly easily, eg get the choices from the database.