4

我有多个相互包含的模板,例如:

t1.html:

...
<%include file="t2.html" args="docTitle='blablabla'" />
...

t2.html:

<%page args="docTitle='Undefined'"/>
<title>${docTitle}</title>
...

而我想要做的是确定 t2 包含在 t1 (或另一个,所以我可以使用它的名字)。文档中没有描述的具体方式引起了我的注意,我本可以传递另一个参数(例如 pagename='foobar'),但感觉更像是一种 hack。

有没有办法做到这一点,使用简单的 .render(blabla) 调用来呈现页面?

4

1 回答 1

1

据我所知,mako 没有提供有关要包含的“父”模板的任何信息。此外,从传递到包含文件的上下文中删除任何有关该信息的信息需要一些注意。

因此,我看到的唯一解决方案是使用 CPython 堆栈,找到最近的 mako 模板框架并从中提取所需的信息。然而,这可能既慢又不可靠,我建议明确传递名称。它还依赖于未记录的 mako 功能,这些功能可能会在以后更改。

这是基于堆栈的解决方案:

在模板中:

${h.get_previous_template_name()} # h is pylons-style helpers module. Substitute it with cherrypy appropriate way.

在 helpers.py 中(或 w/e 适用于cherrypy):

import inspect

def get_previous_template_name():
    stack = inspect.stack()
    for frame_tuple in stack[2:]:
        frame = frame_tuple[0]
        if '_template_uri' in frame.f_globals:
            return frame.f_globals['_template_uri']

但是,这将返回完整的 uri,例如“t1.html”。调整它以满足您的需求。

于 2010-08-01T18:16:12.647 回答