-
-
Save knzm/1877020 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
# -*- coding:utf-8 -*- | |
from mako.template import Template | |
from mako.lookup import TemplateLookup | |
def generate_source_mako(): | |
with open("source.mako", "w") as w: | |
w.write(""" | |
<div id="header"> | |
<%block name="header"> | |
header | |
</%block> | |
</div> | |
<div id="main"> | |
<%block name="main"> | |
main | |
</%block> | |
</div> | |
<div id="footer"> | |
<%block name="footer"> | |
footer | |
</%block> | |
</div> | |
""") | |
def generate_blocks(context, names, dict_name): | |
for name in names: | |
context.write("""\ | |
<%%block name="%s"> | |
${%s["%s"]} | |
</%%block> | |
""" % (name, dict_name, name)) | |
def main(): | |
mylookup = TemplateLookup(directories=["."]) | |
generate_source_mako() | |
template_generate_template = Template("""\ | |
<%text> | |
<%inherit file="source.mako"/> | |
</%text> | |
<%namespace name="smpl" module="sample"/> | |
${smpl.generate_blocks(names, block_name)} | |
""", lookup=mylookup) | |
template_src = template_generate_template.render( | |
names=["header", "main", "footer"], | |
block_name="blocks") | |
template = Template(template_src, lookup=mylookup) | |
output = template.render(blocks={ | |
"header": "<div>header_body</div>", | |
"main": "<p>main_bod</p>", | |
"footer": "<div>footer_body</div>", | |
}) | |
print output | |
""" ## output only once | |
<div id="header"> | |
<div>header_body</div> | |
</div> | |
<div id="main"> | |
<p>main_bod</p> | |
</div> | |
<div id="footer"> | |
<div>footer_body</div> | |
</div> | |
""" | |
# should be output twice | |
print "Hi!" | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment