On 12/2/05, Jiri Barton <[EMAIL PROTECTED]> wrote:
> 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?

Hey Jiri,

Sounds like a good use for a custom template tag. You could call it like this:

{% food_menu "tomatoes" %}

Here's one way to do it. The template-tag code would look something
like this (untested):

"""
from django.core.template import Library

register = Library()

def food_menu(food):
    output = ['<ul>']
    for choice in ('mushrooms', 'tomatoes', 'cheese', 'onion'):
        if food == choice:
            output.append('<li class="selected">')
        else:
            output.append('<li>')
        output.append('%s</li>' % choice)
    return '\n'.join(output)
food_menu = register.simple_tag(food_menu)
"""


That uses the "simple_tag" decorator, which is not yet documented;
it's a recent addition to Django (only in the development version, not
in 0.90). You could also use the similarly-new "inclusion_tag" method
of creating custom template tags.


"""
from django.core.template import Library

register = Library()

def food_menu(argument_val):
    return {'menuselection': argument_val}
food_menu = register.inclusion_tag('foodtag',
takes_context=False)(admin_field_line)

"""

...and create a template "foodtag.html" that would contain this:

"""
<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>
"""

This would give you the flexibility of defining that HTML in a
template rather than in Python.

See the source code of
django/contrib/admin/templatetags/admin_modify.py for more custom-tag
examples. Also check out
http://www.djangoproject.com/documentation/templates_python/#writing-custom-template-tags
, which doesn't yet include simple_tag and inclusion_tag but still has
a lot of information.

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com | chicagocrime.org

Reply via email to