Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created February 21, 2012 13:41
Show Gist options
  • Save podhmo/1876634 to your computer and use it in GitHub Desktop.
Save podhmo/1876634 to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
from mako.template import Template
from mako.lookup import TemplateLookup
mylookup = TemplateLookup(directories=["."])
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))
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
""" ## why output 2times?
<div id="header">
<div>header_body</div>
</div>
<div id="main">
<p>main_bod</p>
</div>
<div id="footer">
<div>footer_body</div>
</div>
<div id="header">
<div>header_body</div>
</div>
<div id="main">
<p>main_bod</p>
</div>
<div id="footer">
<div>footer_body</div>
</div>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment