1

如何制作一个行为类似于 simple_tag 或 assignment_tag 的标签,这两者{% mytag %}都是{% mytag as varname %}可能的?使用以下代码,我无法使用{% mytag %}.

@register.assignment_tag
def mytag():
    return 'hello, world!'
4

1 回答 1

1

您可以使用节点,例如:

收件箱.py

from django.template import Library, Node, TemplateSyntaxError

    class InboxOutput(Node):
        def __init__(self, varname=None):
            self.varname = varname

        def render(self, context):
            return ...


    def inbox_count(parser, token):
        """
        Usage::

            {% load inbox %}
            {% inbox_count %}

            {# or assign the value to a variable: #}

            {% inbox_count as my_var %}
            {{ my_var }}

        """
        bits = token.contents.split()
        if len(bits) > 1:
            if len(bits) != 3:
                raise TemplateSyntaxError, "inbox_count tag takes either no arguments or exactly two arguments"
            if bits[1] != 'as':
                raise TemplateSyntaxError, "first argument to inbox_count tag must be 'as'"
            return InboxOutput(bits[2])
        else:
            return InboxOutput()

    register = Library()     
    register.tag('inbox_count', print_inbox_count)
于 2012-04-19T14:37:23.050 回答