1
2
3 """ Templating Helpers.
4
5 Copyright (c) 2012 The PyroScope Project <pyroscope.project@gmail.com>
6 """
7
8
9
10
11
12
13
14
15
16
17
18
19
20 from __future__ import with_statement
21
22 import os
23 from contextlib import closing
24
25
27 """ Simple string interpolation.
28 """
29
31 """ Create template ADT wrapper object.
32 """
33 self.fmt = unicode(fmt)
34 self.mapping = mapping or (lambda _: _)
35 self.__engine__ = "interpolation"
36 self.__file__ = None
37 self.__text__ = ''
38
39
41 """ Returns interpolation string.
42 """
43 return self.fmt
44
45
47 """ Returns interpolation string.
48 """
49 return self.fmt
50
51
53 """ Return expanded template for given variable set.
54 """
55 return self.fmt % self.mapping(variables)
56
57
58 -def preparse(template_text, lookup=None):
59 """ Do any special processing of a template, including recognizing the templating language
60 and resolving file: references, then return an appropriate wrapper object.
61
62 Currently Tempita and Python string interpolation are supported.
63 `lookup` is an optional callable that resolves any ambiguous template path.
64 """
65
66 template_path = None
67 try:
68 is_file = template_text.startswith("file:")
69 except (AttributeError, TypeError):
70 pass
71 else:
72 if is_file:
73 template_path = template_text[5:]
74 if template_path.startswith('/'):
75 template_path = '/' + template_path.lstrip('/')
76 elif template_path.startswith('~'):
77 template_path = os.path.expanduser(template_path)
78 elif lookup:
79 template_path = lookup(template_path)
80
81 with closing(open(template_path, "r")) as handle:
82 template_text = handle.read().rstrip()
83
84 if hasattr(template_text, "__engine__"):
85
86 template = template_text
87 else:
88 if template_text.startswith("{{"):
89 import tempita
90
91 template = tempita.Template(template_text, name=template_path)
92 template.__engine__ = "tempita"
93 else:
94 template = InterpolationTemplate(template_text)
95
96 template.__file__ = template_path
97
98 template.__text__ = template_text
99 return template
100