Sunday, May 19th, 2013

Python Script to encode Django templates

Do you need to display raw Django template code in your Django <1.4 project? Look no further than this script! It's rather crude, but gets the job done. I haven't yet updated a few Django websites to Django 1.5, which has a new template tag to do this for you, so I created this script to use in legacy Django sites, and it works like a charm!

#!/usr/bin/python

import sys

try:
  filename = sys.argv[1]
except IndexError:
  print "This command needs exactly 1 parameter!"
  sys.exit()

data = open(filename, 'r').read()
data = data.replace('{%', '{! templatetag openblock !}').replace('%}', '{! templatetag closeblock !}')
data = data.replace('{{', '{% templatetag openvariable %}').replace('}}', '{% templatetag closevariable %}')

print data.replace('{!', '{%').replace('!}', '%}')

You should Pygments to highlight the syntax like I do on this blog of course. If you are using Django 1.5 or greater, you should use the verbatim template tag over this.

Comment #1: Posted 1 year, 6 months ago by Luper Rouch

Why not use the verbatim tag? https://docs.djangoproject.com/en/dev/ref/templates/builtins/

Comment #2: Posted 1 year, 6 months ago by Stephen Paulger

There is also the templatetag template tag.

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag

Comment #3: Posted 1 year, 6 months ago by Kevin Veroneau

Have you read the actual article or just the title and code? I specifically mention this is for ppl who have yet to upgrade to 1.5 where the new tag now exists. And the code automates the usage of templatetag(as one commenter failed to read the code). Before commenting people, please read the entire post and code and keep your comments intelligent.

Comment #4: Posted 1 year, 6 months ago by maillot de foot

Current blog, fresh information, I read it from time to time!!…

About Me

My Photo
Names Kevin, hugely into UNIX technologies, not just Linux. I've dabbled with the demons, played with the Sun, and now with the Penguins.




Kevin Veroneau Consulting Services
Do you require the services of a Django contractor? Do you need both a website and hosting services? Perhaps I can help.

This Month

If you like what you read, please consider donating to help with hosting costs, and to fund future books to review.

Python Powered | © 2012-2014 Kevin Veroneau