Mercurial > genshi > mirror
annotate markup/template.py @ 70:dd73921530e8 trunk
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
author | cmlenz |
---|---|
date | Tue, 11 Jul 2006 17:40:41 +0000 |
parents | c40a5dcd2b55 |
children | db7c76d337aa |
rev | line source |
---|---|
1 | 1 # -*- coding: utf-8 -*- |
2 # | |
66
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
65
diff
changeset
|
3 # Copyright (C) 2006 Edgewall Software |
1 | 4 # All rights reserved. |
5 # | |
6 # This software is licensed as described in the file COPYING, which | |
7 # you should have received as part of this distribution. The terms | |
66
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
65
diff
changeset
|
8 # are also available at http://markup.edgewall.org/wiki/License. |
1 | 9 # |
10 # This software consists of voluntary contributions made by many | |
11 # individuals. For the exact contribution history, see the revision | |
66
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
65
diff
changeset
|
12 # history and logs, available at http://markup.edgewall.org/log/. |
1 | 13 |
14 """Template engine that is compatible with Kid (http://kid.lesscode.org) to a | |
15 certain extent. | |
16 | |
17 Differences include: | |
18 * No generation of Python code for a template; the template is "interpreted" | |
19 * No support for <?python ?> processing instructions | |
20 * Expressions are evaluated in a more flexible manner, meaning you can use e.g. | |
21 attribute access notation to access items in a dictionary, etc | |
22 * Use of XInclude and match templates instead of Kid's py:extends/py:layout | |
23 directives | |
24 * Real (thread-safe) search path support | |
25 * No dependency on ElementTree (due to the lack of pos info) | |
26 * The original pos of parse events is kept throughout the processing | |
27 pipeline, so that errors can be tracked back to a specific line/column in | |
28 the template file | |
29 * py:match directives use (basic) XPath expressions to match against input | |
30 nodes, making match templates more powerful while keeping the syntax simple | |
31 | |
32 Todo items: | |
33 * Improved error reporting | |
34 * Support for list comprehensions and generator expressions in expressions | |
35 | |
36 Random thoughts: | |
37 * Is there any need to support py:extends and/or py:layout? | |
38 * Could we generate byte code from expressions? | |
39 """ | |
40 | |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
41 try: |
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
42 from collections import deque |
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
43 except ImportError: |
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
44 class deque(list): |
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
45 def appendleft(self, x): self.insert(0, x) |
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
46 def popleft(self): return self.pop(0) |
1 | 47 import compiler |
48 import os | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
49 import posixpath |
1 | 50 import re |
51 from StringIO import StringIO | |
52 | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
53 from markup.core import Attributes, Namespace, Stream, StreamEventKind |
69 | 54 from markup.core import START, END, START_NS, END_NS, TEXT |
1 | 55 from markup.eval import Expression |
69 | 56 from markup.input import XMLParser |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
57 from markup.path import Path |
1 | 58 |
59 __all__ = ['Context', 'BadDirectiveError', 'TemplateError', | |
60 'TemplateSyntaxError', 'TemplateNotFound', 'Template', | |
61 'TemplateLoader'] | |
62 | |
63 | |
64 class TemplateError(Exception): | |
65 """Base exception class for errors related to template processing.""" | |
66 | |
67 | |
68 class TemplateSyntaxError(TemplateError): | |
69 """Exception raised when an expression in a template causes a Python syntax | |
70 error.""" | |
71 | |
72 def __init__(self, message, filename='<string>', lineno=-1, offset=-1): | |
73 if isinstance(message, SyntaxError) and message.lineno is not None: | |
74 message = str(message).replace(' (line %d)' % message.lineno, '') | |
75 TemplateError.__init__(self, message) | |
76 self.filename = filename | |
77 self.lineno = lineno | |
78 self.offset = offset | |
79 | |
80 | |
81 class BadDirectiveError(TemplateSyntaxError): | |
82 """Exception raised when an unknown directive is encountered when parsing | |
83 a template. | |
84 | |
85 An unknown directive is any attribute using the namespace for directives, | |
86 with a local name that doesn't match any registered directive. | |
87 """ | |
88 | |
89 def __init__(self, name, filename='<string>', lineno=-1): | |
90 TemplateSyntaxError.__init__(self, 'Bad directive "%s"' % name.localname, | |
91 filename, lineno) | |
92 | |
93 | |
94 class TemplateNotFound(TemplateError): | |
95 """Exception raised when a specific template file could not be found.""" | |
96 | |
97 def __init__(self, name, search_path): | |
98 TemplateError.__init__(self, 'Template "%s" not found' % name) | |
99 self.search_path = search_path | |
100 | |
101 | |
102 class Context(object): | |
103 """A container for template input data. | |
104 | |
105 A context provides a stack of scopes. Template directives such as loops can | |
106 push a new scope on the stack with data that should only be available | |
107 inside the loop. When the loop terminates, that scope can get popped off | |
108 the stack again. | |
109 | |
110 >>> ctxt = Context(one='foo', other=1) | |
111 >>> ctxt.get('one') | |
112 'foo' | |
113 >>> ctxt.get('other') | |
114 1 | |
115 >>> ctxt.push(one='frost') | |
116 >>> ctxt.get('one') | |
117 'frost' | |
118 >>> ctxt.get('other') | |
119 1 | |
120 >>> ctxt.pop() | |
121 >>> ctxt.get('one') | |
122 'foo' | |
123 """ | |
124 | |
125 def __init__(self, **data): | |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
126 self.frames = deque([data]) |
1 | 127 |
128 def __repr__(self): | |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
129 return repr(self.frames) |
1 | 130 |
131 def __setitem__(self, key, value): | |
132 """Set a variable in the current context.""" | |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
133 self.frames[0][key] = value |
1 | 134 |
135 def get(self, key): | |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
136 """Get a variable's value, starting at the current context frame and |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
137 going upward. |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
138 """ |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
139 for frame in self.frames: |
1 | 140 if key in frame: |
141 return frame[key] | |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
142 __getitem__ = get |
1 | 143 |
144 def push(self, **data): | |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
145 """Push a new context frame on the stack.""" |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
146 self.frames.appendleft(data) |
1 | 147 |
148 def pop(self): | |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
149 """Pop the top-most context frame from the stack. |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
150 |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
151 If the stack is empty, an `AssertionError` is raised. |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
152 """ |
70
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
153 #assert self.frames, 'Pop from empty context stack' |
dd73921530e8
Use `collections.deque` for the template context stack on Python 2.4, which improves performance if there are many context frame pop/push operations.
cmlenz
parents:
69
diff
changeset
|
154 self.frames.popleft() |
1 | 155 |
156 | |
157 class Directive(object): | |
158 """Abstract base class for template directives. | |
159 | |
54 | 160 A directive is basically a callable that takes three positional arguments: |
161 `ctxt` is the template data context, `stream` is an iterable over the | |
162 events that the directive applies to, and `directives` is is a list of | |
163 other directives on the same stream that need to be applied. | |
1 | 164 |
165 Directives can be "anonymous" or "registered". Registered directives can be | |
166 applied by the template author using an XML attribute with the | |
167 corresponding name in the template. Such directives should be subclasses of | |
31 | 168 this base class that can be instantiated with the value of the directive |
169 attribute as parameter. | |
1 | 170 |
171 Anonymous directives are simply functions conforming to the protocol | |
172 described above, and can only be applied programmatically (for example by | |
173 template filters). | |
174 """ | |
175 __slots__ = ['expr'] | |
176 | |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
177 def __init__(self, value): |
1 | 178 self.expr = value and Expression(value) or None |
179 | |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
180 def __call__(self, stream, ctxt, directives): |
1 | 181 raise NotImplementedError |
182 | |
183 def __repr__(self): | |
184 expr = '' | |
185 if self.expr is not None: | |
186 expr = ' "%s"' % self.expr.source | |
187 return '<%s%s>' % (self.__class__.__name__, expr) | |
188 | |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
189 def _apply_directives(self, stream, ctxt, directives): |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
190 if directives: |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
191 stream = directives[0](iter(stream), ctxt, directives[1:]) |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
192 return stream |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
193 |
1 | 194 |
195 class AttrsDirective(Directive): | |
196 """Implementation of the `py:attrs` template directive. | |
197 | |
198 The value of the `py:attrs` attribute should be a dictionary. The keys and | |
199 values of that dictionary will be added as attributes to the element: | |
200 | |
201 >>> ctxt = Context(foo={'class': 'collapse'}) | |
61 | 202 >>> tmpl = Template('''<ul xmlns:py="http://markup.edgewall.org/"> |
1 | 203 ... <li py:attrs="foo">Bar</li> |
204 ... </ul>''') | |
205 >>> print tmpl.generate(ctxt) | |
206 <ul> | |
207 <li class="collapse">Bar</li> | |
208 </ul> | |
209 | |
210 If the value evaluates to `None` (or any other non-truth value), no | |
211 attributes are added: | |
212 | |
213 >>> ctxt = Context(foo=None) | |
214 >>> print tmpl.generate(ctxt) | |
215 <ul> | |
216 <li>Bar</li> | |
217 </ul> | |
218 """ | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
219 __slots__ = [] |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
220 |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
221 def __call__(self, stream, ctxt, directives): |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
222 def _generate(): |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
223 kind, (tag, attrib), pos = stream.next() |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
224 attrs = self.expr.evaluate(ctxt) |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
225 if attrs: |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
226 attrib = Attributes(attrib[:]) |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
227 if not isinstance(attrs, list): # assume it's a dict |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
228 attrs = attrs.items() |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
229 for name, value in attrs: |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
230 if value is None: |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
231 attrib.remove(name) |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
232 else: |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
233 attrib.set(name, unicode(value).strip()) |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
234 yield kind, (tag, attrib), pos |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
235 for event in stream: |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
236 yield event |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
237 return self._apply_directives(_generate(), ctxt, directives) |
1 | 238 |
239 | |
240 class ContentDirective(Directive): | |
241 """Implementation of the `py:content` template directive. | |
242 | |
243 This directive replaces the content of the element with the result of | |
244 evaluating the value of the `py:content` attribute: | |
245 | |
246 >>> ctxt = Context(bar='Bye') | |
61 | 247 >>> tmpl = Template('''<ul xmlns:py="http://markup.edgewall.org/"> |
1 | 248 ... <li py:content="bar">Hello</li> |
249 ... </ul>''') | |
250 >>> print tmpl.generate(ctxt) | |
251 <ul> | |
252 <li>Bye</li> | |
253 </ul> | |
254 """ | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
255 __slots__ = [] |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
256 |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
257 def __call__(self, stream, ctxt, directives): |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
258 def _generate(): |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
259 kind, data, pos = stream.next() |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
260 if kind is Stream.START: |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
261 yield kind, data, pos # emit start tag |
69 | 262 yield EXPR, self.expr, pos |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
263 previous = stream.next() |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
264 for event in stream: |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
265 previous = event |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
266 if previous is not None: |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
267 yield previous |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
268 return self._apply_directives(_generate(), ctxt, directives) |
1 | 269 |
270 | |
271 class DefDirective(Directive): | |
272 """Implementation of the `py:def` template directive. | |
273 | |
274 This directive can be used to create "Named Template Functions", which | |
275 are template snippets that are not actually output during normal | |
276 processing, but rather can be expanded from expressions in other places | |
277 in the template. | |
278 | |
279 A named template function can be used just like a normal Python function | |
280 from template expressions: | |
281 | |
282 >>> ctxt = Context(bar='Bye') | |
61 | 283 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 284 ... <p py:def="echo(greeting, name='world')" class="message"> |
285 ... ${greeting}, ${name}! | |
286 ... </p> | |
287 ... ${echo('hi', name='you')} | |
288 ... </div>''') | |
289 >>> print tmpl.generate(ctxt) | |
290 <div> | |
291 <p class="message"> | |
292 hi, you! | |
293 </p> | |
294 </div> | |
295 | |
296 >>> ctxt = Context(bar='Bye') | |
61 | 297 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 298 ... <p py:def="echo(greeting, name='world')" class="message"> |
299 ... ${greeting}, ${name}! | |
300 ... </p> | |
301 ... <div py:replace="echo('hello')"></div> | |
302 ... </div>''') | |
303 >>> print tmpl.generate(ctxt) | |
304 <div> | |
305 <p class="message"> | |
306 hello, world! | |
307 </p> | |
308 </div> | |
309 """ | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
310 __slots__ = ['name', 'args', 'defaults', 'stream', 'directives'] |
1 | 311 |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
312 ATTRIBUTE = 'function' |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
313 |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
314 def __init__(self, args): |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
315 Directive.__init__(self, None) |
1 | 316 ast = compiler.parse(args, 'eval').node |
317 self.args = [] | |
318 self.defaults = {} | |
319 if isinstance(ast, compiler.ast.CallFunc): | |
320 self.name = ast.node.name | |
321 for arg in ast.args: | |
322 if isinstance(arg, compiler.ast.Keyword): | |
323 self.args.append(arg.name) | |
324 self.defaults[arg.name] = arg.expr.value | |
325 else: | |
326 self.args.append(arg.name) | |
327 else: | |
328 self.name = ast.name | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
329 self.stream, self.directives = [], [] |
1 | 330 |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
331 def __call__(self, stream, ctxt, directives): |
1 | 332 self.stream = list(stream) |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
333 self.directives = directives |
1 | 334 ctxt[self.name] = lambda *args, **kwargs: self._exec(ctxt, *args, |
335 **kwargs) | |
336 return [] | |
337 | |
338 def _exec(self, ctxt, *args, **kwargs): | |
339 scope = {} | |
340 args = list(args) # make mutable | |
341 for name in self.args: | |
342 if args: | |
343 scope[name] = args.pop(0) | |
344 else: | |
345 scope[name] = kwargs.pop(name, self.defaults.get(name)) | |
346 ctxt.push(**scope) | |
69 | 347 for event in self._apply_directives(self.stream, ctxt, self.directives): |
1 | 348 yield event |
349 ctxt.pop() | |
350 | |
351 | |
352 class ForDirective(Directive): | |
31 | 353 """Implementation of the `py:for` template directive for repeating an |
354 element based on an iterable in the context data. | |
1 | 355 |
356 >>> ctxt = Context(items=[1, 2, 3]) | |
61 | 357 >>> tmpl = Template('''<ul xmlns:py="http://markup.edgewall.org/"> |
1 | 358 ... <li py:for="item in items">${item}</li> |
359 ... </ul>''') | |
360 >>> print tmpl.generate(ctxt) | |
361 <ul> | |
362 <li>1</li><li>2</li><li>3</li> | |
363 </ul> | |
364 """ | |
365 __slots__ = ['targets'] | |
366 | |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
367 ATTRIBUTE = 'each' |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
368 |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
369 def __init__(self, value): |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
370 targets, value = value.split(' in ', 1) |
1 | 371 self.targets = [str(name.strip()) for name in targets.split(',')] |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
372 Directive.__init__(self, value) |
1 | 373 |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
374 def __call__(self, stream, ctxt, directives): |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
375 iterable = self.expr.evaluate(ctxt) |
1 | 376 if iterable is not None: |
377 stream = list(stream) | |
378 for item in iter(iterable): | |
379 if len(self.targets) == 1: | |
380 item = [item] | |
381 scope = {} | |
382 for idx, name in enumerate(self.targets): | |
383 scope[name] = item[idx] | |
384 ctxt.push(**scope) | |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
385 for event in self._apply_directives(stream, ctxt, directives): |
1 | 386 yield event |
387 ctxt.pop() | |
388 | |
389 def __repr__(self): | |
390 return '<%s "%s in %s">' % (self.__class__.__name__, | |
391 ', '.join(self.targets), self.expr.source) | |
392 | |
393 | |
394 class IfDirective(Directive): | |
31 | 395 """Implementation of the `py:if` template directive for conditionally |
396 excluding elements from being output. | |
1 | 397 |
398 >>> ctxt = Context(foo=True, bar='Hello') | |
61 | 399 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 400 ... <b py:if="foo">${bar}</b> |
401 ... </div>''') | |
402 >>> print tmpl.generate(ctxt) | |
403 <div> | |
404 <b>Hello</b> | |
405 </div> | |
406 """ | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
407 __slots__ = [] |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
408 |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
409 ATTRIBUTE = 'test' |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
410 |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
411 def __call__(self, stream, ctxt, directives): |
1 | 412 if self.expr.evaluate(ctxt): |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
413 return self._apply_directives(stream, ctxt, directives) |
1 | 414 return [] |
415 | |
416 | |
417 class MatchDirective(Directive): | |
418 """Implementation of the `py:match` template directive. | |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
419 |
61 | 420 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
421 ... <span py:match="greeting"> |
1 | 422 ... Hello ${select('@name')} |
423 ... </span> | |
424 ... <greeting name="Dude" /> | |
425 ... </div>''') | |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
426 >>> print tmpl.generate() |
1 | 427 <div> |
428 <span> | |
429 Hello Dude | |
430 </span> | |
431 </div> | |
432 """ | |
433 __slots__ = ['path', 'stream'] | |
434 | |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
435 ATTRIBUTE = 'path' |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
436 |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
437 def __init__(self, value): |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
438 Directive.__init__(self, None) |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
439 self.path = Path(value) |
1 | 440 self.stream = [] |
441 | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
442 def __call__(self, stream, ctxt, directives): |
1 | 443 self.stream = list(stream) |
38
ee669cb9cccc
Fix for #2 (incorrect context node in path expressions). Still some paths that produce incorrect results, but the common case seems to work now.
cmlenz
parents:
37
diff
changeset
|
444 ctxt._match_templates.append((self.path.test(ignore_context=True), |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
445 self.path, self.stream, directives)) |
1 | 446 return [] |
447 | |
448 def __repr__(self): | |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
449 return '<%s "%s">' % (self.__class__.__name__, self.path.source) |
1 | 450 |
451 | |
452 class ReplaceDirective(Directive): | |
453 """Implementation of the `py:replace` template directive. | |
454 | |
31 | 455 This directive replaces the element with the result of evaluating the |
456 value of the `py:replace` attribute: | |
457 | |
1 | 458 >>> ctxt = Context(bar='Bye') |
61 | 459 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 460 ... <span py:replace="bar">Hello</span> |
461 ... </div>''') | |
462 >>> print tmpl.generate(ctxt) | |
463 <div> | |
464 Bye | |
465 </div> | |
466 | |
467 This directive is equivalent to `py:content` combined with `py:strip`, | |
468 providing a less verbose way to achieve the same effect: | |
469 | |
470 >>> ctxt = Context(bar='Bye') | |
61 | 471 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 472 ... <span py:content="bar" py:strip="">Hello</span> |
473 ... </div>''') | |
474 >>> print tmpl.generate(ctxt) | |
475 <div> | |
476 Bye | |
477 </div> | |
478 """ | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
479 __slots__ = [] |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
480 |
54 | 481 def __call__(self, stream, ctxt, directives): |
1 | 482 kind, data, pos = stream.next() |
69 | 483 yield EXPR, self.expr, pos |
1 | 484 |
485 | |
486 class StripDirective(Directive): | |
487 """Implementation of the `py:strip` template directive. | |
488 | |
489 When the value of the `py:strip` attribute evaluates to `True`, the element | |
490 is stripped from the output | |
491 | |
61 | 492 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 493 ... <div py:strip="True"><b>foo</b></div> |
494 ... </div>''') | |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
495 >>> print tmpl.generate() |
1 | 496 <div> |
497 <b>foo</b> | |
498 </div> | |
499 | |
37
37557b8fb925
Moved some of the tests for the strip directive to a new unittest test case to not clutter up the documentation.
cmlenz
parents:
36
diff
changeset
|
500 Leaving the attribute value empty is equivalent to a truth value. |
1 | 501 |
502 This directive is particulary interesting for named template functions or | |
503 match templates that do not generate a top-level element: | |
504 | |
61 | 505 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 506 ... <div py:def="echo(what)" py:strip=""> |
507 ... <b>${what}</b> | |
508 ... </div> | |
509 ... ${echo('foo')} | |
510 ... </div>''') | |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
511 >>> print tmpl.generate() |
1 | 512 <div> |
513 <b>foo</b> | |
514 </div> | |
515 """ | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
516 __slots__ = [] |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
517 |
54 | 518 def __call__(self, stream, ctxt, directives): |
1 | 519 if self.expr: |
520 strip = self.expr.evaluate(ctxt) | |
521 else: | |
522 strip = True | |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
523 stream = self._apply_directives(stream, ctxt, directives) |
1 | 524 if strip: |
525 stream.next() # skip start tag | |
526 previous = stream.next() | |
527 for event in stream: | |
528 yield previous | |
529 previous = event | |
530 else: | |
531 for event in stream: | |
532 yield event | |
533 | |
534 | |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
535 class ChooseDirective(Directive): |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
536 """Implementation of the `py:choose` directive for conditionally selecting |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
537 one of several body elements to display. |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
538 |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
539 If the `py:choose` expression is empty the expressions of nested `py:when` |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
540 directives are tested for truth. The first true `py:when` body is output. |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
541 If no `py:when` directive is matched then the fallback directive |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
542 `py:otherwise` will be used. |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
543 |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
544 >>> ctxt = Context() |
61 | 545 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/" |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
546 ... py:choose=""> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
547 ... <span py:when="0 == 1">0</span> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
548 ... <span py:when="1 == 1">1</span> |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
549 ... <span py:otherwise="">2</span> |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
550 ... </div>''') |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
551 >>> print tmpl.generate(ctxt) |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
552 <div> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
553 <span>1</span> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
554 </div> |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
555 |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
556 If the `py:choose` directive contains an expression, the nested `py:when` |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
557 directives are tested for equality to the `py:choose` expression: |
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
558 |
61 | 559 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/" |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
560 ... py:choose="2"> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
561 ... <span py:when="1">1</span> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
562 ... <span py:when="2">2</span> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
563 ... </div>''') |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
564 >>> print tmpl.generate(ctxt) |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
565 <div> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
566 <span>2</span> |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
567 </div> |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
568 |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
569 Behavior is undefined if a `py:choose` block contains content outside a |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
570 `py:when` or `py:otherwise` block. Behavior is also undefined if a |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
571 `py:otherwise` occurs before `py:when` blocks. |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
572 """ |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
573 __slots__ = ['matched', 'value'] |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
574 |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
575 ATTRIBUTE = 'test' |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
576 |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
577 def __call__(self, stream, ctxt, directives): |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
578 if self.expr: |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
579 self.value = self.expr.evaluate(ctxt) |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
580 self.matched = False |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
581 ctxt.push(_choose=self) |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
582 for event in self._apply_directives(stream, ctxt, directives): |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
583 yield event |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
584 ctxt.pop() |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
585 |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
586 |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
587 class WhenDirective(Directive): |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
588 """Implementation of the `py:when` directive for nesting in a parent with |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
589 the `py:choose` directive. |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
590 |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
591 See the documentation of `py:choose` for usage. |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
592 """ |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
593 |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
594 ATTRIBUTE = 'test' |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
595 |
54 | 596 def __call__(self, stream, ctxt, directives): |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
597 choose = ctxt['_choose'] |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
598 if choose.matched: |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
599 return [] |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
600 value = self.expr.evaluate(ctxt) |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
601 try: |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
602 if value == choose.value: |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
603 choose.matched = True |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
604 return self._apply_directives(stream, ctxt, directives) |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
605 except AttributeError: |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
606 if value: |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
607 choose.matched = True |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
608 return self._apply_directives(stream, ctxt, directives) |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
609 return [] |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
610 |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
611 |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
612 class OtherwiseDirective(Directive): |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
613 """Implementation of the `py:otherwise` directive for nesting in a parent |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
614 with the `py:choose` directive. |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
615 |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
616 See the documentation of `py:choose` for usage. |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
617 """ |
54 | 618 def __call__(self, stream, ctxt, directives): |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
619 choose = ctxt['_choose'] |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
620 if choose.matched: |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
621 return [] |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
622 choose.matched = True |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
623 return self._apply_directives(stream, ctxt, directives) |
44
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
624 |
436e30c8420b
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
625 |
1 | 626 class Template(object): |
627 """Can parse a template and transform it into the corresponding output | |
628 based on context data. | |
629 """ | |
61 | 630 NAMESPACE = Namespace('http://markup.edgewall.org/') |
1 | 631 |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
632 EXPR = StreamEventKind('EXPR') # an expression |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
633 SUB = StreamEventKind('SUB') # a "subprogram" |
10
f77f7a91aa46
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
6
diff
changeset
|
634 |
1 | 635 directives = [('def', DefDirective), |
636 ('match', MatchDirective), | |
637 ('for', ForDirective), | |
638 ('if', IfDirective), | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
639 ('when', WhenDirective), |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
640 ('otherwise', OtherwiseDirective), |
53
512eb72dbb19
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
641 ('choose', ChooseDirective), |
1 | 642 ('replace', ReplaceDirective), |
643 ('content', ContentDirective), | |
644 ('attrs', AttrsDirective), | |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
645 ('strip', StripDirective)] |
1 | 646 _dir_by_name = dict(directives) |
647 _dir_order = [directive[1] for directive in directives] | |
648 | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
649 def __init__(self, source, basedir=None, filename=None): |
1 | 650 """Initialize a template from either a string or a file-like object.""" |
651 if isinstance(source, basestring): | |
652 self.source = StringIO(source) | |
653 else: | |
654 self.source = source | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
655 self.basedir = basedir |
1 | 656 self.filename = filename or '<string>' |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
657 if basedir and filename: |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
658 self.filepath = os.path.join(basedir, filename) |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
659 else: |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
660 self.filepath = '<string>' |
1 | 661 |
23
d88358f719fa
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
662 self.filters = [] |
1 | 663 self.parse() |
664 | |
665 def __repr__(self): | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
666 return '<%s "%s">' % (self.__class__.__name__, self.filename) |
1 | 667 |
668 def parse(self): | |
669 """Parse the template. | |
670 | |
671 The parsing stage parses the XML template and constructs a list of | |
672 directives that will be executed in the render stage. The input is | |
673 split up into literal output (markup that does not depend on the | |
674 context data) and actual directives (commands or variable | |
675 substitution). | |
676 """ | |
677 stream = [] # list of events of the "compiled" template | |
678 dirmap = {} # temporary mapping of directives to elements | |
679 ns_prefix = {} | |
680 depth = 0 | |
681 | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
682 for kind, data, pos in XMLParser(self.source, filename=self.filename): |
1 | 683 |
69 | 684 if kind is START_NS: |
1 | 685 # Strip out the namespace declaration for template directives |
686 prefix, uri = data | |
687 if uri == self.NAMESPACE: | |
688 ns_prefix[prefix] = uri | |
689 else: | |
690 stream.append((kind, data, pos)) | |
691 | |
69 | 692 elif kind is END_NS: |
1 | 693 if data in ns_prefix: |
694 del ns_prefix[data] | |
695 else: | |
696 stream.append((kind, data, pos)) | |
697 | |
69 | 698 elif kind is START: |
1 | 699 # Record any directive attributes in start tags |
700 tag, attrib = data | |
701 directives = [] | |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
702 strip = False |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
703 |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
704 if tag in self.NAMESPACE: |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
705 cls = self._dir_by_name.get(tag.localname) |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
706 if cls is None: |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
707 raise BadDirectiveError(tag, pos[0], pos[1]) |
66
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
65
diff
changeset
|
708 value = attrib.get(getattr(cls, 'ATTRIBUTE', None), '') |
59eb24184e9c
Switch copyright to Edgewall and URLs to markup.edgewall.org.
cmlenz
parents:
65
diff
changeset
|
709 directives.append(cls(value)) |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
710 strip = True |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
711 |
1 | 712 new_attrib = [] |
713 for name, value in attrib: | |
18
5420cfe42d36
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
714 if name in self.NAMESPACE: |
1 | 715 cls = self._dir_by_name.get(name.localname) |
716 if cls is None: | |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
717 raise BadDirectiveError(name, pos[0], pos[1]) |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
718 directives.append(cls(value)) |
1 | 719 else: |
720 value = list(self._interpolate(value, *pos)) | |
721 new_attrib.append((name, value)) | |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
722 |
1 | 723 if directives: |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
724 directives.sort(lambda a, b: cmp(self._dir_order.index(a.__class__), |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
725 self._dir_order.index(b.__class__))) |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
726 dirmap[(depth, tag)] = (directives, len(stream), strip) |
1 | 727 |
728 stream.append((kind, (tag, Attributes(new_attrib)), pos)) | |
729 depth += 1 | |
730 | |
69 | 731 elif kind is END: |
1 | 732 depth -= 1 |
733 stream.append((kind, data, pos)) | |
734 | |
735 # If there have have directive attributes with the corresponding | |
736 # start tag, move the events inbetween into a "subprogram" | |
737 if (depth, data) in dirmap: | |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
738 directives, start_offset, strip = dirmap.pop((depth, data)) |
1 | 739 substream = stream[start_offset:] |
65
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
740 if strip: |
b3fdf93057ab
Support the use of directives as elements to reduce the need for using `py:strip`.
cmlenz
parents:
61
diff
changeset
|
741 substream = substream[1:-1] |
69 | 742 stream[start_offset:] = [(SUB, (directives, substream), |
743 pos)] | |
1 | 744 |
69 | 745 elif kind is TEXT: |
1 | 746 for kind, data, pos in self._interpolate(data, *pos): |
747 stream.append((kind, data, pos)) | |
748 | |
749 else: | |
750 stream.append((kind, data, pos)) | |
751 | |
752 self.stream = stream | |
753 | |
754 _FULL_EXPR_RE = re.compile(r'(?<!\$)\$\{(.+?)\}') | |
755 _SHORT_EXPR_RE = re.compile(r'(?<!\$)\$([a-zA-Z][a-zA-Z0-9_\.]*)') | |
756 | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
757 def _interpolate(cls, text, filename=None, lineno=-1, offset=-1): |
1 | 758 """Parse the given string and extract expressions. |
759 | |
760 This method returns a list containing both literal text and `Expression` | |
761 objects. | |
14
c7d33e0c9839
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
762 |
1 | 763 @param text: the text to parse |
764 @param lineno: the line number at which the text was found (optional) | |
765 @param offset: the column number at which the text starts in the source | |
766 (optional) | |
767 """ | |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
768 patterns = [Template._FULL_EXPR_RE, Template._SHORT_EXPR_RE] |
1 | 769 def _interpolate(text): |
770 for idx, group in enumerate(patterns.pop(0).split(text)): | |
771 if idx % 2: | |
69 | 772 yield EXPR, Expression(group), (lineno, offset) |
1 | 773 elif group: |
774 if patterns: | |
775 for result in _interpolate(group): | |
776 yield result | |
777 else: | |
69 | 778 yield TEXT, group.replace('$$', '$'), (filename, lineno, |
779 offset) | |
1 | 780 return _interpolate(text) |
781 _interpolate = classmethod(_interpolate) | |
782 | |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
783 def generate(self, ctxt=None): |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
784 """Apply the template to the given context data. |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
785 |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
786 @param ctxt: a `Context` instance containing the data for the template |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
787 @return: a markup event stream representing the result of applying |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
788 the template to the context data. |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
789 """ |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
790 if ctxt is None: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
791 ctxt = Context() |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
792 if not hasattr(ctxt, '_match_templates'): |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
793 ctxt._match_templates = [] |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
794 |
69 | 795 stream = self.stream |
796 for filter_ in [self._eval, self._match, self._flatten] + self.filters: | |
35
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
797 stream = filter_(iter(stream), ctxt) |
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
798 return Stream(stream) |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
799 |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
800 def _eval(self, stream, ctxt=None): |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
801 """Internal stream filter that evaluates any expressions in `START` and |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
802 `TEXT` events. |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
803 """ |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
804 for kind, data, pos in stream: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
805 |
69 | 806 if kind is START: |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
807 # Attributes may still contain expressions in start tags at |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
808 # this point, so do some evaluation |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
809 tag, attrib = data |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
810 new_attrib = [] |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
811 for name, substream in attrib: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
812 if isinstance(substream, basestring): |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
813 value = substream |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
814 else: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
815 values = [] |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
816 for subkind, subdata, subpos in substream: |
69 | 817 if subkind is EXPR: |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
818 values.append(subdata.evaluate(ctxt)) |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
819 else: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
820 values.append(subdata) |
48
a5d585dd38c4
convert the result of expressions in attributes to strings so that values like ints are output correctly
mgood
parents:
44
diff
changeset
|
821 value = [unicode(x) for x in values if x is not None] |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
822 if not value: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
823 continue |
23
d88358f719fa
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
824 new_attrib.append((name, u''.join(value))) |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
825 yield kind, (tag, Attributes(new_attrib)), pos |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
826 |
69 | 827 elif kind is EXPR: |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
828 result = data.evaluate(ctxt) |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
829 if result is None: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
830 continue |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
831 |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
832 # First check for a string, otherwise the iterable test below |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
833 # succeeds, and the string will be chopped up into individual |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
834 # characters |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
835 if isinstance(result, basestring): |
69 | 836 yield TEXT, result, pos |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
837 else: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
838 # Test if the expression evaluated to an iterable, in which |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
839 # case we yield the individual items |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
840 try: |
35
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
841 for event in self._match(self._eval(iter(result), ctxt), |
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
842 ctxt): |
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
843 yield event |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
844 except TypeError: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
845 # Neither a string nor an iterable, so just pass it |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
846 # through |
69 | 847 yield TEXT, unicode(result), pos |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
848 |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
849 else: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
850 yield kind, data, pos |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
851 |
23
d88358f719fa
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
852 def _flatten(self, stream, ctxt=None): |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
853 """Internal stream filter that expands `SUB` events in the stream.""" |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
854 try: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
855 for kind, data, pos in stream: |
69 | 856 if kind is SUB: |
35
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
857 # This event is a list of directives and a list of nested |
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
858 # events to which those directives should be applied |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
859 directives, substream = data |
69 | 860 if directives: |
861 substream = directives[0](iter(substream), ctxt, | |
862 directives[1:]) | |
863 for filter_ in (self._eval, self._match, self._flatten): | |
864 substream = filter_(substream, ctxt) | |
865 for event in substream: | |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
866 yield event |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
867 continue |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
868 else: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
869 yield kind, data, pos |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
870 except SyntaxError, err: |
69 | 871 raise TemplateSyntaxError(err, pos[0], pos[1], |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
872 pos[2] + (err.offset or 0)) |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
873 |
36
ed370ebfa794
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
874 def _match(self, stream, ctxt=None, match_templates=None): |
29
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
875 """Internal stream filter that applies any defined match templates |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
876 to the stream. |
ab8703fa68b8
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
877 """ |
36
ed370ebfa794
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
878 if match_templates is None: |
ed370ebfa794
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
879 match_templates = ctxt._match_templates |
ed370ebfa794
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
880 |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
881 for kind, data, pos in stream: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
882 |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
883 # We (currently) only care about start and end events for matching |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
884 # We might care about namespace events in the future, though |
69 | 885 if kind not in (START, END): |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
886 yield kind, data, pos |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
887 continue |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
888 |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
889 for idx, (test, path, template, directives) in \ |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
890 enumerate(match_templates): |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
891 result = test(kind, data, pos) |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
892 |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
893 if result: |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
894 # Consume and store all events until an end event |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
895 # corresponding to this start event is encountered |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
896 content = [(kind, data, pos)] |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
897 depth = 1 |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
898 while depth > 0: |
69 | 899 ev = stream.next() |
900 depth += {START: 1, END: -1}.get(ev[0], 0) | |
901 content.append(ev) | |
902 test(*ev) | |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
903 |
23
d88358f719fa
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
904 content = list(self._flatten(content, ctxt)) |
35
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
905 ctxt.push(select=lambda path: Stream(content).select(path)) |
36
ed370ebfa794
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
906 |
50
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
907 if directives: |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
908 template = directives[0](iter(template), ctxt, |
d3842cd76e92
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
909 directives[1:]) |
69 | 910 for event in self._match(self._eval(template, ctxt), |
911 ctxt, match_templates[:idx] + | |
912 match_templates[idx + 1:]): | |
35
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
913 yield event |
35b9e9318fb1
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
914 ctxt.pop() |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
915 |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
916 break |
69 | 917 |
918 else: # no matches | |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
919 yield kind, data, pos |
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
920 |
1 | 921 |
69 | 922 EXPR = Template.EXPR |
923 SUB = Template.SUB | |
924 | |
925 | |
1 | 926 class TemplateLoader(object): |
927 """Responsible for loading templates from files on the specified search | |
928 path. | |
929 | |
930 >>> import tempfile | |
931 >>> fd, path = tempfile.mkstemp(suffix='.html', prefix='template') | |
932 >>> os.write(fd, '<p>$var</p>') | |
933 11 | |
934 >>> os.close(fd) | |
935 | |
936 The template loader accepts a list of directory paths that are then used | |
937 when searching for template files, in the given order: | |
938 | |
939 >>> loader = TemplateLoader([os.path.dirname(path)]) | |
940 | |
941 The `load()` method first checks the template cache whether the requested | |
942 template has already been loaded. If not, it attempts to locate the | |
943 template file, and returns the corresponding `Template` object: | |
944 | |
945 >>> template = loader.load(os.path.basename(path)) | |
946 >>> isinstance(template, Template) | |
947 True | |
948 | |
949 Template instances are cached: requesting a template with the same name | |
950 results in the same instance being returned: | |
951 | |
952 >>> loader.load(os.path.basename(path)) is template | |
953 True | |
954 """ | |
955 def __init__(self, search_path=None, auto_reload=False): | |
956 """Create the template laoder. | |
957 | |
958 @param search_path: a list of absolute path names that should be | |
959 searched for template files | |
960 @param auto_reload: whether to check the last modification time of | |
961 template files, and reload them if they have changed | |
962 """ | |
963 self.search_path = search_path | |
964 if self.search_path is None: | |
965 self.search_path = [] | |
966 self.auto_reload = auto_reload | |
967 self._cache = {} | |
968 self._mtime = {} | |
969 | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
970 def load(self, filename, relative_to=None): |
1 | 971 """Load the template with the given name. |
972 | |
22
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
973 If the `filename` parameter is relative, this method searches the search |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
974 path trying to locate a template matching the given name. If the file |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
975 name is an absolute path, the search path is not bypassed. |
1 | 976 |
22
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
977 If requested template is not found, a `TemplateNotFound` exception is |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
978 raised. Otherwise, a `Template` object is returned that represents the |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
979 parsed template. |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
980 |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
981 Template instances are cached to avoid having to parse the same |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
982 template file more than once. Thus, subsequent calls of this method |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
983 with the same template file name will return the same `Template` |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
984 object (unless the `auto_reload` option is enabled and the file was |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
985 changed since the last parse.) |
1 | 986 |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
987 If the `relative_to` parameter is provided, the `filename` is |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
988 interpreted as being relative to that path. |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
989 |
1 | 990 @param filename: the relative path of the template file to load |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
991 @param relative_to: the filename of the template from which the new |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
992 template is being loaded, or `None` if the template is being loaded |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
993 directly |
1 | 994 """ |
69 | 995 from markup.filters import IncludeFilter |
996 | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
997 if relative_to: |
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
998 filename = posixpath.join(posixpath.dirname(relative_to), filename) |
1 | 999 filename = os.path.normpath(filename) |
22
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1000 |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1001 # First check the cache to avoid reparsing the same file |
1 | 1002 try: |
1003 tmpl = self._cache[filename] | |
1004 if not self.auto_reload or \ | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
1005 os.path.getmtime(tmpl.filepath) == self._mtime[filename]: |
1 | 1006 return tmpl |
1007 except KeyError: | |
1008 pass | |
22
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1009 |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1010 # Bypass the search path if the filename is absolute |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1011 search_path = self.search_path |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1012 if os.path.isabs(filename): |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1013 search_path = [os.path.dirname(filename)] |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1014 |
2483fe549959
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
1015 for dirname in search_path: |
1 | 1016 filepath = os.path.join(dirname, filename) |
1017 try: | |
1018 fileobj = file(filepath, 'rt') | |
1019 try: | |
21
b4d17897d053
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
1020 tmpl = Template(fileobj, basedir=dirname, filename=filename) |
17
74cc70129d04
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
1021 tmpl.filters.append(IncludeFilter(self)) |
1 | 1022 finally: |
1023 fileobj.close() | |
1024 self._cache[filename] = tmpl | |
1025 self._mtime[filename] = os.path.getmtime(filepath) | |
1026 return tmpl | |
1027 except IOError: | |
1028 continue | |
1029 raise TemplateNotFound(filename, self.search_path) |