Created
March 8, 2011 17:51
-
-
Save mikeboers/860643 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
import re | |
from mako.template import Template | |
source = '''pre %{for i in range(10)} | |
${- i -} | |
%{- if i % 2 -} | |
- | |
%{- else -} | |
| | |
%{- endif -} | |
%{- endfor} post''' | |
def _inline_callback(m): | |
statement = m.group(1).strip() | |
return '\\\n%% %s%s\n' % (statement, '' if statement.startswith('end') else ':') | |
_inline_re = re.compile(r'%{([^}]+)}') | |
def inline_control_statements(source): | |
return _inline_re.sub(_inline_callback, source) | |
_post_white_re = re.compile(r'([$%]){(.*?)-}\s*') | |
_pre_white_re = re.compile(r'\s*([$%]){-(.*?)}') | |
def whitespace_control(source): | |
source = _post_white_re.sub(r'\1{\2}', source) | |
return _pre_white_re.sub(r'\1{\2}', source) | |
# Make sure to apply the whitespace control before the inline control statments. | |
template = Template(source, preprocessor=lambda x: inline_control_statements(whitespace_control(x))) | |
print template.code | |
print template.render_unicode() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment