2010-08-10 22 views
2

我正在寫一個自定義模板標籤'firstnotnone',類似於Django的'firstof'模板標籤。如何使用可變長度參數?下面的代碼導致TemplateSyntaxError,firstnotnone接受1個參數。如何製作可變長度arg列表的django自定義模板標籤

模板:

{% load library %} 
{% firstnotnone 'a' 'b' 'c' %} 

自定義模板標籤庫:

@register.simple_tag 
def firstnotnone(*args): 
    print args 
    for arg in args: 
     if arg is not None: 
      return arg 

回答

2

定製templatetags:

from django.template import Library, Node, TemplateSyntaxError 
from django.utils.encoding import smart_unicode 

register = Library() 

class FirstNotNoneNode(Node): 
    def __init__(self, vars): 
     self.vars = vars 

    def render(self, context): 
     for var in self.vars: 
      value = var.resolve(context, True) 
      if value is not None: 
       return smart_unicode(value) 
     return u'' 

def firstnotnone(parser,token): 
    """ 
    Outputs the first variable passed that is not None 
    """ 
    bits = token.split_contents()[1:] 
    if len(bits) < 1: 
     raise TemplateSyntaxError("'firstnotnone' statement requires at least one argument") 
    return FirstNotNoneNode([parser.compile_filter(bit) for bit in bits]) 

firstnotnone = register.tag(firstnotnone) 
+1

感謝,代碼看上去幹淨。太糟糕了,它不能用可變長度的參數列表來完成。 – 2010-08-11 12:37:46

+0

你確定它不能? – MattH 2010-08-11 12:42:44

+0

@Jack Ha:它處理可變長度參數列表,我甚至測試過它。據我所知,這是一個你正在要求的實現。 – MattH 2010-08-11 13:22:33

4

firstof標籤不通過simple_tag裝飾來實現 - 它採用了template.Node子和一個單獨的標籤的長形功能。您可以在django.template.defaulttags中看到代碼 - 爲了您的目的而進行更改應該相當簡單。

相關問題