如何告诉 Django 模板不要解析包含看起来像模板标签的代码的块?

Posted

技术标签:

【中文标题】如何告诉 Django 模板不要解析包含看起来像模板标签的代码的块?【英文标题】:How can I tell Django templates not to parse a block containing code that looks like template tags? 【发布时间】:2011-12-30 22:22:54 【问题描述】:

我有一些 html 文件,其中包含 jQuery.tmpl 使用的模板。一些 tmpl 标签(如 if...)看起来像 Django 模板标签并导致 TemplateSyntaxError。有没有办法可以指定 Django 模板系统应该忽略几行并完全按原样输出?

【问题讨论】:

【参考方案1】:

从 Django 1.5 开始,现在由内置的 verbatim 模板标签处理。

在旧版本的 Django 中,内置方法是使用 templatetag 模板标签 (https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#templatetag) 手动转义每个模板项,但我怀疑这不是您想要做的。

您真正想要的是一种将整个块标记为原始(而不是可解释)文本的方法,这需要一个新的自定义标记。您可能想在这里查看raw 标签:http://www.holovaty.com/writing/django-two-phased-rendering/

【讨论】:

【参考方案2】:

有几个公开票可以解决这个问题:https://code.djangoproject.com/ticket/14502 和 https://code.djangoproject.com/ticket/16318 您可以在下面找到建议的新模板标签verbatim

"""
From https://gist.github.com/1313862
"""

from django import template

register = template.Library()


class VerbatimNode(template.Node):

    def __init__(self, text):
        self.text = text

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


@register.tag
def verbatim(parser, token):
    text = []
    while 1:
        token = parser.tokens.pop(0)
        if token.contents == 'endverbatim':
            break
        if token.token_type == template.TOKEN_VAR:
            text.append('')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append('%')
        text.append(token.contents)
        if token.token_type == template.TOKEN_VAR:
            text.append('')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append('%')
    return VerbatimNode(''.join(text))

【讨论】:

我认为raw 标签比这些标签更优雅。加上verbatim 不处理评论标签和noparse 返回和空字符串。 如果您有这种感觉,请务必对相关票证发表评论。社区决定了 Django 的功能。我并不是说这是最好的方法,而是社区目前正在朝着这个方向发展。 经过仔细检查,很明显 noparse 会遍历块中的标记并将它们全部设置为文本标记。

以上是关于如何告诉 Django 模板不要解析包含看起来像模板标签的代码的块?的主要内容,如果未能解决你的问题,请参考以下文章