~jonas-drange/ubuntu-start-page/1252899-mobile-friendly

« back to all changes in this revision

Viewing changes to src/mako/ext/autohandler.py

  • Committer: Matthew Nuzum
  • Date: 2008-04-18 01:58:53 UTC
  • Revision ID: matthew.nuzum@canonical.com-20080418015853-2b8rf979z2c2exxl
adding files

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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.access(d + '/' + psub, os.F_OK):
 
54
            return True
 
55
    else:
 
56
        return False
 
57
    
 
 
b'\\ No newline at end of file'