views:

67

answers:

2

Hi Guys,

I have a model with a bunch of choices, that are in the DB configured as below.

COL_CHOICES =(
            (1, 'Not Applicable'),
            (2, 'Black'),
        )

COL2_CHOICES =(
            (1, 'Green'),
            (2, 'Blue'),
        )

etc.

I want to display all these options as a menu in my templates, (to be used as a menu). Since these options are stored in the code, it does not make sense to query the DB. What would be the best way to make these available?

They should be available on all pages, Template Tags would be the way to go. However what would the template tag look like?

Update I have tried the FFQ template tag:

class OptionsNode(Node):
    def __init__(self, colours, varname):
        self.colours = colours
        self.varname = varname

    def render(self, context):
        context[self.varname] = self.colours
        return ''

def get_options(parser, token):
    return OptionsNode(COLOUR_CHOICES, 'colour')

Update2 So the above code works, and you access the values by using colour.1 / colour.2 etc for each value respectively.

See below for full answer

A: 

If they're in the code, you can pass them directly to the template context:

render_to_response('mytemplate.html', {
                      'col_choices': COL_CHOICES,
                      'col2_choices': COL2_CHOICES
                   })

Edit in response to comment: If you need this on every page including generic views, the best thing to do is to use a template tag.

Daniel Roseman
Daniel, thanks for a response, would this be in a view? What about generic views and if you need them available on all pages?
izzy
See my response above.
Daniel Roseman
Thanks for the response. When i try to return the COL_OPTIONS, all i get is a tuple back in the template and i cant access each option individually or loop over it.
izzy
A: 

Since no one has posted a sufficient enough response, here is it if you are looking to do something similar. If anyone can think of a more effective way of doing this i would be glad to hear it. :

You need to import your choices from your models file.

class OptionsNode(Node):
    def __init__(self, options, varname):
        self.options = options
        self.varname = varname

    def render(self, context):
        context[self.varname] = self.options
        return ''

def get_options(parser, token):
    bits = token.contents.split()

    if len(bits) !=4:
        raise TemplateSyntaxError, "get_options tag takes exactly Four arguments"
    if bits[2] != 'as':
        raise TemplateSyntaxError, "Third argument to get_options tag must be 'as'"
    if bits[1] == 'COL_CHOICES':
        choice = COL_CHOICES 
    return OptionsNode(choice, bits[3])

get_options = register.tag(get_options)

In the template you use:

{% get_options your_choices as variable %}
izzy