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

2

16

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 TemplateSyntaxError. Is there a way I can specify the Django template system should ignore a few lines and output them exactly as they are?

Nympholepsy answered 17/11, 2011 at 0:27 Comment(0)
N
24

As of Django 1.5, this is now handled by the built-in verbatim template tag.

In older versions of Django, the built-in way would be to manually escape each template item with the templatetag template tag ( https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#templatetag ), but I suspect that that's not what you want to do.

What you really want is a way to mark a whole block as raw (rather than interpretable) text, which requires a new custom tag. You might want to check out the raw tag here: http://www.holovaty.com/writing/django-two-phased-rendering/

Nightrider answered 17/11, 2011 at 0:38 Comment(0)
M
5

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))
Mulry answered 17/11, 2011 at 1:11 Comment(3)
I think the raw tag is a more elegant solution than these ones. Plus verbatim doesn't handle comment tags and noparse returns and empty string.Nympholepsy
If you feel that way you should be sure to comment on the relevant tickets. It's the community that decides what features are going into Django. I'm not saying this is the best way to do it but this is what the community is currently moving towards.Mulry
On closer inspection it's clear that noparse traverses the tokens in the block and sets them all to Text Tokens.Nympholepsy

© 2022 - 2024 — McMap. All rights reserved.