Easy Way to Escape Django Template Variables

后端 未结 6 897
礼貌的吻别
礼貌的吻别 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

    A possible solution is to write the templates as usual (with {{ x }}), but save them as .txt (or any other extension you want). Write a script the runs over these files, and automatically creates the .html for you, by doing the reverse of templatetag (replacing {{ with {% templatetag openvariable %}etc). Make sure the code runs after you update the templates.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-04 06:38

    Django 1.5 solves this problem with the verbatim template tag. It also works fine with the current Django versions.

    {% verbatim myblock %}
        Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
    {% endverbatim myblock %}
    
    0 讨论(0)
  • 2021-02-04 06:52

    I solved this by adding an "include_raw" template tag that behaves like the built-in "include" tag, but just doesn't parse or process the file passed to it. I'm running Django 1.2 under App Engine.

    Create a tags module (tags.py):

    from django.template import loader
    from google.appengine.ext.webapp import template
    
    register = template.create_template_register()
    
    @register.simple_tag
    def include_raw(path):
      return loader.find_template(path)[0]
    

    Register it:

    from google.appengine.ext.webapp import template
    
    template.register_template_library("tags")
    

    Use it:

    {% include_raw "this-will-be-included-verbatim.html" %}
    
    0 讨论(0)
  • 2021-02-04 06:58

    If your source is HTML, the easiest solution would be to replace "{" and "}" with their respective HTML entities:

    { becomes {

    } becomes }

    Example:

    <code>
    To include some other file, you can use the &#123;% include %&#125; template tag. 
    To include a variable, use &#123;%&#123;% varname &#125;%&#125;%.
    </code>
    
    0 讨论(0)
  • 2021-02-04 07:02

    Due to limitations in the Django template lexer (like being a kludgy hack), this is impossible. However, if you are willing to put your example code in separate files, you can use the ssi tag:

    {% ssi /path/to/my/code/examples/example01.html %}
    

    And it won't parse the file, just include it verbatim. However, this also has limitations in that you can't use variables in the include path (i.e. if you move template locations, you have to rewrite or at least find-and-replace your template files), and you have to put the include path (i.e. /path/to/my/code/examples) in the ALLOWED_INCLUDE_ROOTS setting in your settings.py. (See http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ssi.)

    0 讨论(0)
提交回复
热议问题