为assignment_tag指定赋值

时间:2012-04-19 14:22:25

标签: django django-templates

如何制作行为与simple_tag或assignment_tag相同的标记,{% mytag %}{% mytag as varname %}都可以?使用以下代码,我无法使用{% mytag %}等标记。

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

1 个答案:

答案 0 :(得分:1)

您可以使用节点,例如:

<强> inbox.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)