How can I tell Django templates not to parse a block containing code that looks like template tags?

后端 未结 2 1014
栀梦
栀梦 2021-02-13 03:56

I\'ve got some html files that include templates to be used by jQuery.tmpl. Some tmpl tags (like {{if...}}) look like Django template tags and cause a TemplateSynta

2条回答
  •  爱一瞬间的悲伤
    2021-02-13 04:35

    There are a couple open ticket to address this issue: https://code.djangoproject.com/ticket/14502 and https://code.djangoproject.com/ticket/16318 You can find a proposed new template tag verbatim below:

    """
    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))
    

提交回复
热议问题