autohandler.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # ext/autohandler.py
  2. # Copyright (C) 2006-2016 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 posixpath
  20. import os
  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. else:
  38. return path
  39. if len(tokens) == 1:
  40. break
  41. tokens[-2:] = [name]
  42. if not lookup.filesystem_checks:
  43. return lookup._uri_cache.setdefault(
  44. (autohandler, _template_uri, name), None)
  45. else:
  46. return None
  47. def _file_exists(lookup, path):
  48. psub = re.sub(r'^/', '', path)
  49. for d in lookup.directories:
  50. if os.path.exists(d + '/' + psub):
  51. return True
  52. else:
  53. return False