如何创建带可变长度参数列表的Django自定义模板标签

2 投票
2 回答
1214 浏览
提问于 2025-04-16 02:34

我正在写一个自定义的模板标签,叫做'firstnotnone',它的功能类似于Django里的'firstof'标签。请问怎么使用可变长度的参数呢?下面的代码出现了TemplateSyntaxError,提示'firstnotnone'只接受一个参数。

模板:

{% 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 个回答

4

这个 firstof 标签不是通过 simple_tag 装饰器来实现的,而是使用了一种更复杂的方式,涉及到一个 template.Node 的子类和一个单独的标签函数。你可以在 django.template.defaulttags 里找到相关代码,修改起来应该也比较简单,适合你的需求。

2

自定义模板标签:

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)

撰写回答