Skip to content

Instantly share code, notes, and snippets.

@mdipierro
Last active August 29, 2015 13:57
Show Gist options
  • Save mdipierro/9459290 to your computer and use it in GitHub Desktop.
Save mdipierro/9459290 to your computer and use it in GitHub Desktop.
"""
Usage:
python jinja2web2py.py jinjatemplate.html > web2pytemplate.html
Disclaimer. It is not perfect. Some times minor manual tweaks may be necessary.
Notice the web2py template language was invented in 2007 and consists of pure Python code.
The opposite conversion is not possible because arbitrary Python code cannot be converted to a jinja template.
"""
import sys
import re
CONV = [
('\{\{(.*?)\|\s*e\s*\%\}', '{{=\g<1>}}'),
('\{\{(.*?)\}\}', '{{=\g<1>}}'),
('\{\%\s*extends\s+(.*?)\%\}', '{{ extend \g<1>}}'),
('\{\%\s*endblock\s+(.*?)\%\}', '{{ end }}'),
('\{\%\s*macro\s+(.*?)\%\}', '{{ def g<1>: }}'),
('\{\%\s*endmacro\s+(.*?)\%\}', '{{ def g<1>: }}'),
('\{\%\s*endif\s*\%\}', '{{ pass }}'),
('\{\%\s*endfor\s*\%\}', '{{ pass }}'),
('\{\%\s*for\s+(.*?)\s+in\s+(.*?)\s*\|\s*sort\s*\%\}', '{{ for \g<1> in sorted(\g<2>): }}'),
('\{\%\s*(for .*?|if .*?|elif .*?|else)\s*\%\}', '{{ \g<1>: }}'),
('\{\%(.*?)\%\}', '{{\g<1>}}')]
def convert(data):
for a,b in CONV:
data = re.compile(a).sub(b,data)
return data
print convert(open(sys.argv[1]).read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment