views:

32

answers:

1

Hi.

I have multiple templates that include each other, such as :

t1.html :

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

t2.html:

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

And what I want to do is to determine that t2 is included by t1 (or another one, so I can use its name). No specific way described in the documentation caught my eye, and I could've passed yet another argument (such as pagename='foobar'), but it feels more like a hack.

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

+1  A: 

As far as I can tell, mako does not provide any information about 'parent' template to included. Moreover, it takes some care to delete any bits of information on that from context passed to included file.

Therefore only solution I see is to use CPython stack, to find nearest mako template frame and extract needed information from it. However this may be both slow and unreliable, and I would advice going with explicit passing of the name. It also relies on undocumented mako features, which may change later.

Here's stack-based solution:

In the template:

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

In the helpers.py (or w/e is appropriate for 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']

This will return full uri, however, like 't1.html'. Tweak it to fit your needs.

Daniel Kluev