开发者

Use Choices from Models in a template tag

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 开发者_如何学Pythonabove code works, and you access the values by using colour.1 / colour.2 etc for each value respectively.

See below for full answer


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.


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 %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜