如何在使用非文件模板的mako中实现继承?

0 投票
1 回答
1125 浏览
提问于 2025-04-17 15:21

大多数关于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集合。

任何模板都可以通过将“lookup=some_lookup”这个关键字参数传递给Template,或者直接用lookup创建模板字符串,像这样lookup.put("some template name", "your template")来关联一个查找。

我还没有弄明白如何应用这个并把它转换成实际的python代码。

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()

撰写回答