我正在编写一个自定义模板标记“firstnotnone”,类似于Django的“firstof”模板标记。如何使用可变长度参数?下面的代码导致TemplateSyntaxError,firstnotnone接受1个参数。
模板:

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

最佳答案

自定义模板标记:

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)

09-16 00:04