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

Jak*_*ake 14 django django-templates jquery-templates

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

Mic*_*nor 21

从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/


Mar*_*vin 5

有几个打开的门票来解决这个问题:https://code.djangoproject.com/ticket/14502https://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))
Run Code Online (Sandbox Code Playgroud)

  • 如果你有这种感觉,你一定要对相关的门票发表评论.这是社区决定Django的功能.我并不是说这是最好的方式,但这正是社区目前正朝着这个方向发展的. (2认同)