Python Pyramid - 添加多个 chameleon 基础模板

4 投票
1 回答
1626 浏览
提问于 2025-04-16 21:05

我正在使用这个方法来使用一个基础模板,其他模板可以从这个基础模板中派生出来。

我该如何创建多个基础模板呢?

1 个回答

3

只需同时注册这两个:

from pyramid.renderers import get_renderer

def add_base_template(event):
    base = get_renderer('templates/base.pt').implementation()
    base2 = get_renderer('templates/base2.pt').implementation()
    event.update({'base': base, 'base2': base2})

然后在每个页面的模板中选择使用哪个:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:tal="http://xml.zope.org/namespaces/tal"
      xmlns:metal="http://xml.zope.org/namespaces/metal"
      metal:use-macro="base">
    <tal:block metal:fill-slot="content">
        My awesome content.
    </tal:block>
</html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:tal="http://xml.zope.org/namespaces/tal"
      xmlns:metal="http://xml.zope.org/namespaces/metal"
      metal:use-macro="base2">
    <tal:block metal:fill-slot="content">
        Content on a totally different page.
    </tal:block>

我认为模板不一定要是整个HTML元素,所以你可以把两个宏扩展到同一个最终模板中。

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:tal="http://xml.zope.org/namespaces/tal"
      xmlns:metal="http://xml.zope.org/namespaces/metal">
    <body>
        <div metal:use-macro="section1">
            <tal:block metal:fill-slot="content">
                Content for template "section1".
            </tal:block>
        </div>
        <div metal:use-macro="section2">
            <tal:block metal:fill-slot="content">
                Content for template "section2".
            </tal:block>
        </div>
    </body>

撰写回答