Skip to content

Instantly share code, notes, and snippets.

@knzm
Forked from podhmo/sample.py
Created February 21, 2012 15:26
Show Gist options
  • Save knzm/1877020 to your computer and use it in GitHub Desktop.
Save knzm/1877020 to your computer and use it in GitHub Desktop.
# -*- 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