2010-08-01 100 views
4

我有多個模板,包括對方,如:Mako模板:如何找到當前模板包含的模板的名稱?

t1.html:

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

t2.html:

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

我想要做的是確定t2包含在t1中(或另一個,所以我可以使用它的名字)。文檔中描述的具體方式引起了我的注意,我可能已經通過了另一個參數(例如pagename ='foobar'),但它更像是一種黑客攻擊。

有沒有辦法做到這一點,使用簡單的.render(blabla)調用來呈現頁面?

+2

我不認爲在Mako中有一種方法可以執行所需的內省(至少不是以任何干淨的方式!)。 「顯式比隱式更好」遠非「黑客」 - 它是**正常的**,**推薦的** Python方法 - 所以我只想用你正在努力避免的額外參數,根本不認爲它是一個糟糕的解決方案。 – 2010-08-01 17:26:24

+0

我正在使用的應用程序使用'rendertemplate(filename,...)'而不是'.render()'方法,所以我爲該函數提供了一個包裝器,將模板名稱放入參數中。我想可能會爲'render'方法做類似的事情。 – 2016-02-10 06:58:24

回答

1

據我所知,mako沒有提供任何關於'parent'模板的信息。此外,還需要注意刪除傳遞給包含文件的上下文中的任何信息。

因此,我看到的唯一解決方案是使用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'。調整它以適應您的需求。