【问题标题】:How to use inheritance with mako using non-file based templates?如何使用非基于文件的模板将继承与 mako 一起使用?
【发布时间】:2013-01-25 04:31:38
【问题描述】:

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" 关键字参数发送到模板,或通过创建 使用 lookup.put("some 模板名称”、“你的模板”)。

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

【问题讨论】:

    标签: python templates python-2.7 mako


    【解决方案1】:

    首先,您需要将${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()
    

    【讨论】:

      猜你喜欢
      • 2011-04-24
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 2011-11-08
      • 2014-03-03
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      相关资源
      最近更新 更多