Mako templates: how to find the name of a template that includes the current template?

I have several templates that include each other, for example:

t1.html:

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

t2.html:

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

And I want to determine that t2 is turned on by t1 (or another, so I can use its name). No specific method described in the documentation caught my eye and I could pass another argument (e.g. pagename = 'foobar), but it looks more like a hack.

Is there a way to accomplish this using a simple .render (blabla) call to display the page?

+4
source share
1 answer

As far as I can tell, mako does not provide any information about the included "parent" template. Moreover, it is necessary to remove any bits of information from the context transferred to the included file.

Therefore, the only solution I see is to use the CPython stack, search for the closest frame of the mako template, and extract the necessary information from it. However, this can be either slow or unreliable, and I would advise going with the explicit passage of the name. It also relies on mako's undocumented features, which may change later.

Here's a stack based solution:

In the template:

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

In helpers.py (or w / e is suitable for cherry):

 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'] 

This will return the full uri, however, as 't1.html'. Customize it to fit your needs.

+1
source

All Articles