我有多个相互包含的模板,例如:
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) 调用来呈现页面?
最佳答案
据我所知,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”。调整它以满足您的需求。
关于python - Mako 模板 : How to find the name of the template which the current template is included by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3382885/