如何使用金字塔/ ZPT(变色龙)宏

时间:2013-04-10 14:07:21

标签: macros pyramid chameleon template-tal template-metal

我想使用带金字塔+ ZPT引擎(Chameleon)的宏。

文档说“单个页面模板可以容纳多个宏”。 http://chameleon.readthedocs.org/en/latest/reference.html#macros-metal

因此我定义了一个文件 macros.pt

<div metal:define-macro="step-0">
  <p>This is step 0</p>
</div>
<div metal:define-macro="step-1">
  <p>This is step 1</p>
</div>

以及一个全局模板main_template.pt,其中包含定义广告位content的所有html内容。

以及我的观看progress.pt的模板,该模板使用main_template.pt填写广告位:

<html metal:use-macro="load: main_template.pt">
  <div metal:fill-slot="content">
    ...
    <div metal:use-macro="step-0"></div>
    ...
  </div>
</html>

到目前为止,我痛苦地发现,我不能只说use-macro="main_template.pt",因为Chameleon不像Zope那样自动加载模板。因此,我必须先添加load:摘录。

use-macro="step-0"。这会引发step-0的NameError。我尝试使用类似macros.pt的内容预加载<tal:block tal:define="compile load: macros.pt" />,但这没有帮助。

如何使用在宏摘要文件中收集的宏?

1 个答案:

答案 0 :(得分:7)

要在Pyramid中使用ZPT宏,您需要通过将宏模板甚至宏本身传递到呈现的模板(摘录自文档),使宏模板本身可用于呈现的模板。

from pyramid.renderers import get_renderer
from pyramid.view import view_config

@view_config(renderer='templates/progress.pt')
def my_view(request):
    snippets = get_renderer('templates/macros.pt').implementation()
    main = get_renderer('templates/main_template.pt').implementation()
    return {'main':main,'snippets':snippets}

在渲染器将使用的模板中,您应该像这样引用宏。我假设main_template.pt中包含插槽'content'的宏名为'global_layout'。把它改成你的名字。

<html metal:use-macro="main.macros['global_layout']">
  <div metal:fill-slot="content">
    ...
    <div metal:use-macro="snippets.macros['step-0']"></div>
    ...
  </div>
</html>

对模板内部宏的引用如下:

<div metal:use-macro="template.macros['step-0']">
    <div metal:fill-slot="content">
        added your content
    </div>
</div>
<div metal:define-macro="step-0">
    a placeholder for your content
    <div metal:define-slot="content">
    </div>
</div>

要获取模板中的所有宏,以便将它们在视图中传递到渲染模板,请将此行添加到第一个代码示例并扩展返回的字典。

macros = get_renderer('templates/main_template.pt').implementation().macros

我可以解释更多,但请查看文档。这里描述了一个类似上面的简单案例。

完整的教程也介绍了这个主题。第二个链接将提升您的知识。

之后金字塔文档将提供更多细节。欢迎来到金字塔。