在模板标记中使用模型中的选项

时间:2009-10-11 12:45:53

标签: django django-models django-templates

我有一个带有一系列选择的模型,这些选择在DB配置如下。

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

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

我想将所有这些选项显示为模板中的菜单(用作菜单)。由于这些选项存储在代码中,因此查询数据库没有意义。什么是最好的方式来提供这些?

它们应该可以在所有页面上使用,模板标签将是最佳选择。但是模板标签会是什么样子?

更新 我尝试过FFQ模板标签:

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 因此上面的代码可以工作,并且您可以分别使用colour.1 / colour.2等为每个值访问这些值。

请参阅下面的完整答案

2 个答案:

答案 0 :(得分:0)

如果它们在代码中,您可以将它们直接传递给模板上下文:

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

编辑以回复评论:如果您在包含通用视图的每个页面上都需要此功能,那么最好的办法是使用模板标记。

答案 1 :(得分:0)

由于没有人发布足够的回复,如果你想要做类似的事情就是这样的话。如果有人能想出更有效的方法,我会很高兴听到它。 :

您需要从模型文件中导入选择。

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)

在您使用的模板中:

{% get_options your_choices as variable %}