[英]How to use inheritance with mako using non-file based templates?
Most of the examples and tutorials for mako suggest you use files for templates. mako的大多数示例和教程都建议您使用文件作为模板。
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): 作为一个起点,我试图基于mako网站上的基于文件的继承示例创建基于变量的继承示例(之后可以很容易地将其转换为基于数据库的示例):
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. 第二个模板需要某种方式来知道base.html应该是base_template。
This question has also been asked on the mako-discuss group in 2009: 2009年mako-discuss小组也提出了这个问题:
https://groups.google.com/d/topic/mako-discuss/QiwkRu7rTFQ/discussion https://groups.google.com/d/topic/mako-discuss/QiwkRu7rTFQ/discussion
This is what Michael Bayer wrote as an answer: 这就是Michael Bayer写的答案:
A TemplateLookup collection needs to be involved for templates to
模板需要涉及TemplateLookup集合
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").
任何模板都可以使用发送到Template的“lookup = some_lookup”关键字参数与查找相关联,或者使用lookup.put(“某些模板名称”,“您的模板”)直接创建模板字符串。
I could not yet figure out how to apply this and convert it to actual python code. 我还不知道如何应用它并将其转换为实际的python代码。
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. 首先,您需要将
${self.body()}
添加到基础模板,这将标记继承者数据将在那里的位置。 And then you can use TemplateLookup like so: 然后您可以像这样使用TemplateLookup:
from mako.template import Template
from mako.lookup import TemplateLookup
base = """
<html>
<body>
<div class="header">
<%block name="header"/>
</div>
${self.body()}
</body>
</html>
"""
index = """
<%inherit file="base.html"/>
<%block name="header">
this is some header content
</%block>
this is the body content.
"""
lookup = TemplateLookup()
lookup.put_string("base.html", base)
lookup.put_string("index.html", index)
index_template = lookup.get_template("index.html")
print index_template.render()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.