【问题标题】:Use Choices from Models in a template tag在模板标签中使用来自模型的选择
【发布时间】:2010-12-05 18:09:09
【问题描述】:

我有一个模型有很多选择,在数据库中配置如下。

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')

更新2 因此,上面的代码有效,您可以通过使用 colour.1 / colour.2 等来分别访问每个值的值。

完整答案见下文

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

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

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

    根据评论进行编辑:如果您在包括通用视图在内的每个页面上都需要此功能,最好的办法是使用模板标签。

    【讨论】:

    • Daniel,感谢您的回复,这会在视图中吗?通用视图怎么样?如果您需要它们在所有页面上都可用?
    • 感谢您的回复。当我尝试返回 COL_OPTIONS 时,我得到的只是模板中的一个元组,我无法单独访问每个选项或循环访问它。
    【解决方案2】:

    由于没有人发布足够多的回复,如果您想做类似的事情,这里就是。如果有人能想到一种更有效的方法,我会很高兴听到它。 :

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

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

    【讨论】:

      猜你喜欢
      • 2014-03-20
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      相关资源
      最近更新 更多