django自定义标签内联或块

时间:2012-02-16 15:58:21

标签: django google-app-engine django-templates

我想知道是否有办法检查标签是否有端块。我基本上试图让用户做

{% mytag 'a' 'b' 'c' %}

{% mytag 'a' 'b' 'c' %}
    <!-- other markup here -->
{% end mytag %}

我看到它不存在它会引发异常,但有没有办法以编程方式设置我的标签以安全地处理这两种情况?

1 个答案:

答案 0 :(得分:3)

您可以尝试解析直到结束标记,并在未找到时捕获异常。如果您同时运行到另一个mytag节点,则可能需要停止:

def do_mytag_stuff(parser, token):

    # Process your token however you need
    mytag_args = token.split_contents()

    try:
        nodelist = parser.parse(('endmytag', 'mytag'))
        token = parser.next_token()
        if token.contents == 'endmytag':
            # Found an ending tag, make a node for its contents
            parser.delete_first_token()
            return MyTagNode(nodelist, mytag_args)

    except TemplateSyntaxError:
        # Neither tag was found
        pass

    # So either there's no closing tag, or we met another mytag before a closing tag. 
    # Do whatever you would for a single tag here
    return SingleMyTagNode(mytag_args)

不确定这是否100%正确,但希望它会有所帮助。