Easy Way to Escape Django Template Variables

后端 未结 6 987
礼貌的吻别
礼貌的吻别 2021-02-04 06:28

For a new project we\'re writing documentation about the Django template system. We use Django for the documentation project itself too, so Django picks up all our exam

6条回答
  •  轮回少年
    2021-02-04 06:36

    Here is an elegant way to solve to problem for Djano 1.4. It is a Django custom tag. Simply create a module verbatim_templatetag.py containing the following code:

    """
    jQuery templates use constructs like:
    
        {{if condition}} print something{{/if}}
    
    This, of course, completely screws up Django templates,
    because Django thinks {{ and }} mean something.
    
    Wrap {% verbatim %} and {% endverbatim %} around those
    blocks of jQuery templates and this will try its best
    to output the contents with no changes.
    """
    
    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))
    

    Then in your template: {% load verbatim_templatetag %}

    Everything between {% verbatim %} and {% endverbatim %} will not be parsed.

    Code from https://gist.github.com/ericflo/629508

提交回复
热议问题