| 1 | """adds autohandler functionality to Mako templates. | 
|---|
| 2 |  | 
|---|
| 3 | requires that the TemplateLookup class is used with templates. | 
|---|
| 4 |  | 
|---|
| 5 | usage: | 
|---|
| 6 |  | 
|---|
| 7 | <%! | 
|---|
| 8 |         from mako.ext.autohandler import autohandler | 
|---|
| 9 | %> | 
|---|
| 10 | <%inherit file="${autohandler(template, context)}"/> | 
|---|
| 11 |  | 
|---|
| 12 |  | 
|---|
| 13 | or with custom autohandler filename: | 
|---|
| 14 |  | 
|---|
| 15 | <%! | 
|---|
| 16 |         from mako.ext.autohandler import autohandler | 
|---|
| 17 | %> | 
|---|
| 18 | <%inherit file="${autohandler(template, context, name='somefilename')}"/> | 
|---|
| 19 |  | 
|---|
| 20 | """ | 
|---|
| 21 |  | 
|---|
| 22 | import posixpath, os, re | 
|---|
| 23 |  | 
|---|
| 24 | def autohandler(template, context, name='autohandler'): | 
|---|
| 25 |     lookup = context.lookup | 
|---|
| 26 |     _template_uri = template.module._template_uri | 
|---|
| 27 |     if not lookup.filesystem_checks: | 
|---|
| 28 |         try: | 
|---|
| 29 |             return lookup._uri_cache[(autohandler, _template_uri, name)] | 
|---|
| 30 |         except KeyError: | 
|---|
| 31 |             pass | 
|---|
| 32 |  | 
|---|
| 33 |     tokens = re.findall(r'([^/]+)', posixpath.dirname(_template_uri)) + [name] | 
|---|
| 34 |     while len(tokens): | 
|---|
| 35 |         path = '/' + '/'.join(tokens) | 
|---|
| 36 |         if path != _template_uri and _file_exists(lookup, path): | 
|---|
| 37 |             if not lookup.filesystem_checks: | 
|---|
| 38 |                 return lookup._uri_cache.setdefault((autohandler, _template_uri, name), path) | 
|---|
| 39 |             else: | 
|---|
| 40 |                 return path | 
|---|
| 41 |         if len(tokens) == 1: | 
|---|
| 42 |             break | 
|---|
| 43 |         tokens[-2:] = [name] | 
|---|
| 44 |          | 
|---|
| 45 |     if not lookup.filesystem_checks: | 
|---|
| 46 |         return lookup._uri_cache.setdefault((autohandler, _template_uri, name), None) | 
|---|
| 47 |     else: | 
|---|
| 48 |         return None | 
|---|
| 49 |  | 
|---|
| 50 | def _file_exists(lookup, path): | 
|---|
| 51 |     psub = re.sub(r'^/', '',path) | 
|---|
| 52 |     for d in lookup.directories: | 
|---|
| 53 |         if os.path.exists(d + '/' + psub): | 
|---|
| 54 |             return True | 
|---|
| 55 |     else: | 
|---|
| 56 |         return False | 
|---|
| 57 |      | 
|---|