0

mako 的大多数示例和教程都建议您使用文件作为模板。

如果模板存储在字符串或数据库中,如何使用继承?

作为一个起点,我正在尝试基于来自 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()

显然这是行不通的。

第二个模板需要某种方式来知道 base.html 应该是 base_template。

2009 年,mako-discuss 小组也有人问过这个问题:

https://groups.google.com/d/topic/mako-discuss/QiwkRu7rTFQ/discussion

这是迈克尔·拜尔(Michael Bayer)写的答案:

模板相互访问需要用到 TemplateLookup 集合

任何模板都可以使用发送到 Template 的 "lookup=some_lookup" 关键字参数与查找相关联,或者通过使用 lookup.put("some template name", "your template") 直接使用查找创建模板字符串。

我还不知道如何应用它并将其转换为实际的 python 代码。

4

1 回答 1

2

首先,您需要添加${self.body()}到基本模板,这将标记继承者数据所在的位置。然后你可以像这样使用 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()
于 2013-02-09T19:59:37.763 回答