[Fixed]-Easy Way to Escape Django Template Variables

7👍

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

15👍

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 %}

3👍

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.

3👍

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" %}

3👍

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>
👤chrisv

0👍

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

👤gpasse

Leave a comment