Created
March 10, 2014 04:00
-
-
Save mdipierro/9459265 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 Python code cannot be converted to a jinja template. | |
""" | |
import sys | |
import re | |
codee = re.compile('\{\{(.*?)\|\s*e\s*\%\}',re.DOTALL) | |
codeprint = re.compile('\{\{(.*?)\}\}',re.DOTALL) | |
extends = re.compile('\{\%\s*extends\s+(.*?)\%\}',re.DOTALL) | |
endblock = re.compile('\{\%\s*endblock\s+(.*?)\%\}',re.DOTALL) | |
macro = re.compile('\{\%\s*macro\s+(.*?)\%\}',re.DOTALL) | |
endmacro = re.compile('\{\%\s*endmacro\s+(.*?)\%\}',re.DOTALL) | |
endif = re.compile('\{\%\s*endif\s*\%\}',re.DOTALL) | |
endfor = re.compile('\{\%\s*endfor\s*\%\}',re.DOTALL) | |
refor_sort = re.compile('\{\%\s*for\s+(.*?)\s+in\s+(.*?)\s*\|\s*sort\s*\%\}',re.DOTALL) | |
reif = re.compile('\{\%\s*(for .*?|if .*?|elif .*?|else)\s*\%\}',re.DOTALL) | |
code = re.compile('\{\%(.*?)\%\}',re.DOTALL) | |
def convert(data): | |
data = codee.sub('{{=\g<1>}}',data) # web2py always escapes by default | |
data = codeprint.sub('{{=\g<1>}}',data) | |
data = extends.sub('{{ extends \g<1>}}',data) | |
data = endblock.sub('{{ end }}', data) | |
data = macro.sub('{{ def g<1>: }}',data) # web2py invented this, not jinja | |
data = endmacro.sub('{{ return }}',data) | |
data = endif.sub('{{ pass }}',data) | |
data = endfor.sub('{{ pass }}',data) | |
data = refor_sort.sub('{{ for \g<1> in sorted(\g<2>): }}', data) | |
data = reif.sub('{{ \g<1>: }}', data) | |
data = code.sub('{{\g<1>}}',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