【问题标题】:Mako Templates : How to find the name of the template which the current template is included by?Mako Templates : 如何找到包含当前模板的模板名称?
【发布时间】:2011-03-23 21:52:01
【问题描述】:

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

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 没有办法执行您需要的内省(至少不是以任何干净的方式!)。 “显式优于隐式”远非“黑客”——它是正常推荐 Python 方法——所以我只会使用额外的参数你'正在努力避免并且根本不认为这是一个糟糕的解决方案。
  • 我正在开发的应用程序使用rendertemplate(filename, ...) 而不是.render() 方法,因此我为该函数制作了一个包装器,将模板名称放入参数中。我想可以为render 方法做类似的事情。

标签: python cherrypy mako


【解决方案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”。调整它以满足您的需求。

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2014-12-25
    • 1970-01-01
    • 2015-06-27
    • 2013-10-18
    • 2014-06-27
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多