Most of the examples and tutorials for mako suggest you use files for templates.
How can I use inheritance, if the templates are stored in strings or in a database?
As a starting point I am trying to create a variable based inheritance example based on the file-based inheritance example from the mako website (which could be easily converted to a database-based example afterwards):
from mako.template import Template
base = """
<html>
<body>
<div class="header">
<%block name="header"/>
</div>
Some body content ...
</body>
</html>
"""
index = """
<%inherit file="base.html"/>
<%block name="header">
this is some header content
</%block>
this is the body content.
"""
base_template = Template(base)
index_template = Template(index)
print index_template.render()
Obviously this does not work.
The second template needs some way to know that base.html should be base_template.
This question has also been asked on the mako-discuss group in 2009:
https://groups.google.com/d/topic/mako-discuss/QiwkRu7rTFQ/discussion
This is what Michael Bayer wrote as an answer:
A TemplateLookup collection needs to be involved for templates to
access each other.Any template can be associated with a lookup using either the
“lookup=some_lookup” keyword argument sent to Template, or by creating
the Template strings directly with the lookup using lookup.put(“some
template name”, “your template”).
I could not yet figure out how to apply this and convert it to actual python code.
First of all you need to add
${self.body()}to your base template, this will mark the place there the inheritor’s data will go. And then you can use TemplateLookup like so: