2009-10-11 50 views
0

我有一堆模型,其中有一些選項,這些選項在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等每個訪問值值。

請參見下面的完整的答案

回答

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

如果他們在代碼中,你可以將其直接轉給模板背景:響應

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

編輯評論:如果你需要這個在包含通用視圖的每個頁面上,最好的辦法是使用模板標籤。

+0

丹尼爾,感謝的響應,這會是一個看法?通用視圖又如何,如果你需要它們在所有頁面上可用? – ismail 2009-10-11 13:14:27

+0

查看我上面的回覆。 – 2009-10-11 13:46:05

+0

感謝您的回覆。當我嘗試返回COL_OPTIONS時,我得到的是模板中的一個元組,並且我不能單獨訪問每個選項或循環訪問它。 – ismail 2009-10-11 14:12:05