| 1 |
# ext/autohandler.py |
| 2 |
# Copyright 2006-2022 the Mako authors and contributors <see AUTHORS file> |
| 3 |
# |
| 4 |
# This module is part of Mako and is released under |
| 5 |
# the MIT License: http://www.opensource.org/licenses/mit-license.php |
| 6 |
|
| 7 |
"""adds autohandler functionality to Mako templates. |
| 8 |
|
| 9 |
requires that the TemplateLookup class is used with templates. |
| 10 |
|
| 11 |
usage:: |
| 12 |
|
| 13 |
<%! |
| 14 |
from mako.ext.autohandler import autohandler |
| 15 |
%> |
| 16 |
<%inherit file="${autohandler(template, context)}"/> |
| 17 |
|
| 18 |
|
| 19 |
or with custom autohandler filename:: |
| 20 |
|
| 21 |
<%! |
| 22 |
from mako.ext.autohandler import autohandler |
| 23 |
%> |
| 24 |
<%inherit file="${autohandler(template, context, name='somefilename')}"/> |
| 25 |
|
| 26 |
""" |
| 27 |
|
| 28 |
import os |
| 29 |
import posixpath |
| 30 |
import re |
| 31 |
|
| 32 |
|
| 33 |
def autohandler(template, context, name="autohandler"): |
| 34 |
lookup = context.lookup |
| 35 |
_template_uri = template.module._template_uri |
| 36 |
if not lookup.filesystem_checks: |
| 37 |
try: |
| 38 |
return lookup._uri_cache[(autohandler, _template_uri, name)] |
| 39 |
except KeyError: |
| 40 |
pass |
| 41 |
|
| 42 |
tokens = re.findall(r"([^/]+)", posixpath.dirname(_template_uri)) + [name] |
| 43 |
while len(tokens): |
| 44 |
path = "/" + "/".join(tokens) |
| 45 |
if path != _template_uri and _file_exists(lookup, path): |
| 46 |
if not lookup.filesystem_checks: |
| 47 |
return lookup._uri_cache.setdefault( |
| 48 |
(autohandler, _template_uri, name), path |
| 49 |
) |
| 50 |
else: |
| 51 |
return path |
| 52 |
if len(tokens) == 1: |
| 53 |
break |
| 54 |
tokens[-2:] = [name] |
| 55 |
|
| 56 |
if not lookup.filesystem_checks: |
| 57 |
return lookup._uri_cache.setdefault( |
| 58 |
(autohandler, _template_uri, name), None |
| 59 |
) |
| 60 |
else: |
| 61 |
return None |
| 62 |
|
| 63 |
|
| 64 |
def _file_exists(lookup, path): |
| 65 |
psub = re.sub(r"^/", "", path) |
| 66 |
for d in lookup.directories: |
| 67 |
if os.path.exists(d + "/" + psub): |
| 68 |
return True |
| 69 |
else: |
| 70 |
return False |