Skip to content

Instantly share code, notes, and snippets.

@cborgolte
Created May 11, 2012 14:54
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 cborgolte/2660253 to your computer and use it in GitHub Desktop.
Save cborgolte/2660253 to your computer and use it in GitHub Desktop.
Put parts of my django templates in {% blocktrans %}-blocks.
#!/usr/bin/env python
"""
Quick and dirty script I use from within vim to put parts of my django templates in {% blocktrans %}-blocks.
Usage:
Visually mark the code inside vim and then pipe it to this script (:!blocktrans.py)
"""
import sys
import re
import sha
m = re.compile('{{\s?(\w+[\.\|].+?)\s?\}\}')
varlist = {}
lines = []
for line in sys.stdin.readlines():
vars_ = m.findall(line)
for var in vars_:
sha_ = sha.sha(var).hexdigest()
substitutes = var.split('|', 1)
substitutes[0] = substitutes[0].replace('.', '_')
substitute = substitutes[0]
if len(substitutes) > 1:
substitute += '_' + sha_[:4]
varlist[var] = substitute
line = line.replace(var, substitute)
lines.append(line)
if varlist:
print "{{% blocktrans with {0} %}}".format(' '.join(('{1}={0}'.format(*item) for item in varlist.iteritems())))
else:
print "{% blocktrans %}"
print ''.join(lines),
print "{% endblocktrans %}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment