3

我想使用带有金字塔+ZPT 引擎(变色龙)的宏。

文档说“一个页面模板可以容纳多个宏”。 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,其中包含定义 slot 的所有 html 内容content

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". 这会引发 NameError step-0。我试图用类似的macros.pt东西预加载,<tal:block tal:define="compile load: macros.pt" />但这没有帮助。

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

4

1 回答 1

7

要在 Pyramid 中使用 ZPT 宏,您需要通过将宏模板甚至宏本身传递到渲染模板中来使宏模板本身可用于渲染模板(摘自 docs)。

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 中包含插槽“内容”的宏被命名为“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

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

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

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

于 2013-04-13T20:23:07.490 回答