autohandler.py 1.8 KB

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