定製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)
感謝,代碼看上去幹淨。太糟糕了,它不能用可變長度的參數列表來完成。 – 2010-08-11 12:37:46
你確定它不能? – MattH 2010-08-11 12:42:44
@Jack Ha:它處理可變長度參數列表,我甚至測試過它。據我所知,這是一個你正在要求的實現。 – MattH 2010-08-11 13:22:33