Skip to content

Instantly share code, notes, and snippets.

@andrusha
Forked from ericflo/verbatim_templatetag.py
Created April 17, 2012 23:10
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save andrusha/2409775 to your computer and use it in GitHub Desktop.
Save andrusha/2409775 to your computer and use it in GitHub Desktop.
"""
jQuery templates use constructs like:
{{if condition}} print something{{/if}}
Or like:
{% if condition %} print {%=object.something %}{% endif %}
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:
if not text[-1].startswith('='):
text[-1:-1] = [' ']
text.append(' %}')
return VerbatimNode(''.join(text))
@memogarcia
Copy link

is this work for django 1.4?

@andrusha
Copy link
Author

andrusha commented Aug 6, 2013

@memogarcia, I guess I'm too late, but yes, it does.

@poorevil
Copy link

very good!!
Thank u~

@iLaus
Copy link

iLaus commented Aug 12, 2015

'module' object has no attribute 'TOKEN_VAR'
D:\Python34\lib\site-packages\django-1.8.2-py3.4.egg\django\template\base.py in parse, line 341

may I know that what is 'TOKEN_VAR' ?

@ajoyoommen
Copy link

'module' object has no attribute 'TOKEN_VAR'
DJANGO 1.8.4

From Django 1.8, TOKEN_VAR and TOKEN_BLOCK must be imported from django.template.base

@rririanto
Copy link

rririanto commented May 16, 2016

I also have same error in django 1.8 has no attribute 'module' object has no attribute 'TOKEN_TEXT'

so i have modify some line to this.

from django import template as templates
from django.template import base as template
register = templates.Library()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment