Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Forked from mdipierro/jinja2web2py.py
Created March 10, 2014 04:58
Show Gist options
  • Save rochacbruno/9459705 to your computer and use it in GitHub Desktop.
Save rochacbruno/9459705 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