【问题标题】:how to use macros with pyramid / ZPT (Chameleon)如何在金字塔 / ZPT(变色龙)中使用宏
【发布时间】:2013-04-02 10:22:36
【问题描述】:

我想使用带有金字塔+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,其中包含定义插槽 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: sn-p。

来到use-macro="step-0"。这会引发 step-0 的 NameError。我试图用&lt;tal:block tal:define="compile load: macros.pt" /&gt; 之类的东西预加载macros.pt,但这没有帮助。

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

【问题讨论】:

  • 从 Zope 页面模板的经验来看,我希望 tal:define="macros_template load: macros.pt" metal:use-macro="macros_template.macros['step-0']" 能够工作;每个模板对象都有一个macros 属性和键per 包含宏。不过还没试过变色龙。

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


【解决方案1】:

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

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

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

之后,金字塔文档将提供更多详细信息。欢迎来到金字塔。

【讨论】:

  • 我怎样才能使用在同一个文件中定义的宏?
  • 我使用 Chameleon 文档提供的信息和我已经提到的链接扩展了答案。请下次再问一个问题。祝这个话题好运。
  • 最后两个链接坏了。
猜你喜欢
  • 2011-08-27
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 2011-12-07
  • 2011-12-25
  • 1970-01-01
相关资源
最近更新 更多