Skip to content

Instantly share code, notes, and snippets.

@jeffkistler
Created April 15, 2011 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffkistler/920931 to your computer and use it in GitHub Desktop.
Save jeffkistler/920931 to your computer and use it in GitHub Desktop.
Template tag for passing through template code.
from django import template
register = template.Library()
TOKEN_PAIRS = {
template.TOKEN_VAR: (template.VARIABLE_TAG_START, template.VARIABLE_TAG_END),
template.TOKEN_BLOCK: (template.BLOCK_TAG_START, template.BLOCK_TAG_END),
template.TOKEN_COMMENT: (template.COMMENT_TAG_START, template.COMMENT_TAG_END),
}
class VerbatimNode(template.Node):
def __init__(self, contents):
self.contents = contents
def render(self, context):
return self.contents
def compile_verbatim(parser, token):
"""
Pass through contents unmolested to the rendered template.
Usage::
{% verbatim %}
{{ some_var }}{% some_tag %}{# some comment #}
{% endverbatim %}
"""
try:
(tag_name,) = token.split_contents()
end_tag = 'end%s' % tag_name
except ValueError:
raise template.TemplateSyntaxError('%s tag takes no arguments' % token.contents.split()[0])
contents = []
while True:
if not parser.tokens:
raise template.TemplateSyntaxError('No %s tag found.' % end_tag)
token = parser.next_token()
if token.token_type == template.TOKEN_BLOCK and token.contents == end_tag:
break
if token.token_type != template.TOKEN_TEXT:
start, end = TOKEN_PAIRS[token.token_type]
contents.extend([start, ' ', token.contents, ' ', end])
else:
contents.append(token.contents)
return VerbatimNode(''.join(contents))
register.tag('verbatim', compile_verbatim)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment