Mercurial > genshi > mirror
annotate markup/template.py @ 5:dbb08edbc615 trunk
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
author | cmlenz |
---|---|
date | Sat, 03 Jun 2006 15:29:27 +0000 |
parents | 5479aae32f5a |
children | 71e8e645fe81 |
rev | line source |
---|---|
1 | 1 # -*- coding: utf-8 -*- |
2 # | |
3 # Copyright (C) 2006 Christopher Lenz | |
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 | |
8 # are also available at http://trac.edgewall.com/license.html. | |
9 # | |
10 # This software consists of voluntary contributions made by many | |
11 # individuals. For the exact contribution history, see the revision | |
12 # history and logs, available at http://projects.edgewall.com/trac/. | |
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 using directives as elements and not just as attributes, reducing | |
35 the need for wrapper elements with py:strip="" | |
36 * Support for py:choose/py:when/py:otherwise (similar to XSLT) | |
37 * Support for list comprehensions and generator expressions in expressions | |
38 | |
39 Random thoughts: | |
40 * Is there any need to support py:extends and/or py:layout? | |
41 * Could we generate byte code from expressions? | |
42 """ | |
43 | |
44 import compiler | |
45 from itertools import chain | |
46 import os | |
47 import re | |
48 from StringIO import StringIO | |
49 | |
50 from markup.core import Attributes, Stream | |
51 from markup.eval import Expression | |
52 from markup.filters import EvalFilter, IncludeFilter, MatchFilter, \ | |
53 WhitespaceFilter | |
54 from markup.input import HTML, XMLParser, XML | |
55 | |
56 __all__ = ['Context', 'BadDirectiveError', 'TemplateError', | |
57 'TemplateSyntaxError', 'TemplateNotFound', 'Template', | |
58 'TemplateLoader'] | |
59 | |
60 | |
61 class TemplateError(Exception): | |
62 """Base exception class for errors related to template processing.""" | |
63 | |
64 | |
65 class TemplateSyntaxError(TemplateError): | |
66 """Exception raised when an expression in a template causes a Python syntax | |
67 error.""" | |
68 | |
69 def __init__(self, message, filename='<string>', lineno=-1, offset=-1): | |
70 if isinstance(message, SyntaxError) and message.lineno is not None: | |
71 message = str(message).replace(' (line %d)' % message.lineno, '') | |
72 TemplateError.__init__(self, message) | |
73 self.filename = filename | |
74 self.lineno = lineno | |
75 self.offset = offset | |
76 | |
77 | |
78 class BadDirectiveError(TemplateSyntaxError): | |
79 """Exception raised when an unknown directive is encountered when parsing | |
80 a template. | |
81 | |
82 An unknown directive is any attribute using the namespace for directives, | |
83 with a local name that doesn't match any registered directive. | |
84 """ | |
85 | |
86 def __init__(self, name, filename='<string>', lineno=-1): | |
87 TemplateSyntaxError.__init__(self, 'Bad directive "%s"' % name.localname, | |
88 filename, lineno) | |
89 | |
90 | |
91 class TemplateNotFound(TemplateError): | |
92 """Exception raised when a specific template file could not be found.""" | |
93 | |
94 def __init__(self, name, search_path): | |
95 TemplateError.__init__(self, 'Template "%s" not found' % name) | |
96 self.search_path = search_path | |
97 | |
98 | |
99 class Context(object): | |
100 """A container for template input data. | |
101 | |
102 A context provides a stack of scopes. Template directives such as loops can | |
103 push a new scope on the stack with data that should only be available | |
104 inside the loop. When the loop terminates, that scope can get popped off | |
105 the stack again. | |
106 | |
107 >>> ctxt = Context(one='foo', other=1) | |
108 >>> ctxt.get('one') | |
109 'foo' | |
110 >>> ctxt.get('other') | |
111 1 | |
112 >>> ctxt.push(one='frost') | |
113 >>> ctxt.get('one') | |
114 'frost' | |
115 >>> ctxt.get('other') | |
116 1 | |
117 >>> ctxt.pop() | |
118 >>> ctxt.get('one') | |
119 'foo' | |
120 """ | |
121 | |
122 def __init__(self, **data): | |
123 self.stack = [data] | |
124 | |
125 def __getitem__(self, key): | |
126 """Get a variable's value, starting at the current context and going | |
127 upward. | |
128 """ | |
129 return self.get(key) | |
130 | |
131 def __repr__(self): | |
132 return repr(self.stack) | |
133 | |
134 def __setitem__(self, key, value): | |
135 """Set a variable in the current context.""" | |
136 self.stack[0][key] = value | |
137 | |
138 def get(self, key): | |
139 for frame in self.stack: | |
140 if key in frame: | |
141 return frame[key] | |
142 | |
143 def push(self, **data): | |
144 self.stack.insert(0, data) | |
145 | |
146 def pop(self): | |
147 assert self.stack, 'Pop from empty context stack' | |
148 self.stack.pop(0) | |
149 | |
150 | |
151 class Directive(object): | |
152 """Abstract base class for template directives. | |
153 | |
154 A directive is basically a callable that takes two parameters: `ctxt` is | |
155 the template data context, and `stream` is an iterable over the events that | |
156 the directive applies to. | |
157 | |
158 Directives can be "anonymous" or "registered". Registered directives can be | |
159 applied by the template author using an XML attribute with the | |
160 corresponding name in the template. Such directives should be subclasses of | |
161 this base class that can be instantiated with two parameters: `template` | |
162 is the `Template` instance, and `value` is the value of the directive | |
163 attribute. | |
164 | |
165 Anonymous directives are simply functions conforming to the protocol | |
166 described above, and can only be applied programmatically (for example by | |
167 template filters). | |
168 """ | |
169 __slots__ = ['expr'] | |
170 | |
171 def __init__(self, template, value, pos): | |
172 self.expr = value and Expression(value) or None | |
173 | |
174 def __call__(self, stream, ctxt): | |
175 raise NotImplementedError | |
176 | |
177 def __repr__(self): | |
178 expr = '' | |
179 if self.expr is not None: | |
180 expr = ' "%s"' % self.expr.source | |
181 return '<%s%s>' % (self.__class__.__name__, expr) | |
182 | |
183 | |
184 class AttrsDirective(Directive): | |
185 """Implementation of the `py:attrs` template directive. | |
186 | |
187 The value of the `py:attrs` attribute should be a dictionary. The keys and | |
188 values of that dictionary will be added as attributes to the element: | |
189 | |
190 >>> ctxt = Context(foo={'class': 'collapse'}) | |
191 >>> tmpl = Template('''<ul xmlns:py="http://purl.org/kid/ns#"> | |
192 ... <li py:attrs="foo">Bar</li> | |
193 ... </ul>''') | |
194 >>> print tmpl.generate(ctxt) | |
195 <ul> | |
196 <li class="collapse">Bar</li> | |
197 </ul> | |
198 | |
199 If the value evaluates to `None` (or any other non-truth value), no | |
200 attributes are added: | |
201 | |
202 >>> ctxt = Context(foo=None) | |
203 >>> print tmpl.generate(ctxt) | |
204 <ul> | |
205 <li>Bar</li> | |
206 </ul> | |
207 """ | |
208 def __call__(self, stream, ctxt): | |
209 kind, (tag, attrib), pos = stream.next() | |
210 attrs = self.expr.evaluate(ctxt) | |
211 if attrs: | |
5
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
212 attrib = Attributes(attrib[:]) |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
213 if not isinstance(attrs, list): # assume it's a dict |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
214 attrs = attrs.items() |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
215 for name, value in attrs: |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
216 if value is None: |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
217 attrib.remove(name) |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
218 else: |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
219 attrib.set(name, unicode(value).strip()) |
dbb08edbc615
Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents:
1
diff
changeset
|
220 yield kind, (tag, attrib), pos |
1 | 221 for event in stream: |
222 yield event | |
223 | |
224 | |
225 class ContentDirective(Directive): | |
226 """Implementation of the `py:content` template directive. | |
227 | |
228 This directive replaces the content of the element with the result of | |
229 evaluating the value of the `py:content` attribute: | |
230 | |
231 >>> ctxt = Context(bar='Bye') | |
232 >>> tmpl = Template('''<ul xmlns:py="http://purl.org/kid/ns#"> | |
233 ... <li py:content="bar">Hello</li> | |
234 ... </ul>''') | |
235 >>> print tmpl.generate(ctxt) | |
236 <ul> | |
237 <li>Bye</li> | |
238 </ul> | |
239 """ | |
240 def __call__(self, stream, ctxt): | |
241 kind, data, pos = stream.next() | |
242 if kind is Stream.START: | |
243 yield kind, data, pos # emit start tag | |
244 yield Stream.EXPR, self.expr, pos | |
245 previous = None | |
246 try: | |
247 while True: | |
248 previous = stream.next() | |
249 except StopIteration: | |
250 if previous is not None: | |
251 yield previous | |
252 | |
253 | |
254 class DefDirective(Directive): | |
255 """Implementation of the `py:def` template directive. | |
256 | |
257 This directive can be used to create "Named Template Functions", which | |
258 are template snippets that are not actually output during normal | |
259 processing, but rather can be expanded from expressions in other places | |
260 in the template. | |
261 | |
262 A named template function can be used just like a normal Python function | |
263 from template expressions: | |
264 | |
265 >>> ctxt = Context(bar='Bye') | |
266 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
267 ... <p py:def="echo(greeting, name='world')" class="message"> | |
268 ... ${greeting}, ${name}! | |
269 ... </p> | |
270 ... ${echo('hi', name='you')} | |
271 ... </div>''') | |
272 >>> print tmpl.generate(ctxt) | |
273 <div> | |
274 <p class="message"> | |
275 hi, you! | |
276 </p> | |
277 </div> | |
278 | |
279 >>> ctxt = Context(bar='Bye') | |
280 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
281 ... <p py:def="echo(greeting, name='world')" class="message"> | |
282 ... ${greeting}, ${name}! | |
283 ... </p> | |
284 ... <div py:replace="echo('hello')"></div> | |
285 ... </div>''') | |
286 >>> print tmpl.generate(ctxt) | |
287 <div> | |
288 <p class="message"> | |
289 hello, world! | |
290 </p> | |
291 </div> | |
292 """ | |
293 __slots__ = ['name', 'args', 'defaults', 'stream'] | |
294 | |
295 def __init__(self, template, args, pos): | |
296 Directive.__init__(self, template, None, pos) | |
297 ast = compiler.parse(args, 'eval').node | |
298 self.args = [] | |
299 self.defaults = {} | |
300 if isinstance(ast, compiler.ast.CallFunc): | |
301 self.name = ast.node.name | |
302 for arg in ast.args: | |
303 if isinstance(arg, compiler.ast.Keyword): | |
304 self.args.append(arg.name) | |
305 self.defaults[arg.name] = arg.expr.value | |
306 else: | |
307 self.args.append(arg.name) | |
308 else: | |
309 self.name = ast.name | |
310 self.stream = [] | |
311 | |
312 def __call__(self, stream, ctxt): | |
313 self.stream = list(stream) | |
314 ctxt[self.name] = lambda *args, **kwargs: self._exec(ctxt, *args, | |
315 **kwargs) | |
316 return [] | |
317 | |
318 def _exec(self, ctxt, *args, **kwargs): | |
319 scope = {} | |
320 args = list(args) # make mutable | |
321 for name in self.args: | |
322 if args: | |
323 scope[name] = args.pop(0) | |
324 else: | |
325 scope[name] = kwargs.pop(name, self.defaults.get(name)) | |
326 ctxt.push(**scope) | |
327 for event in self.stream: | |
328 yield event | |
329 ctxt.pop() | |
330 | |
331 | |
332 class ForDirective(Directive): | |
333 """Implementation of the `py:for` template directive. | |
334 | |
335 >>> ctxt = Context(items=[1, 2, 3]) | |
336 >>> tmpl = Template('''<ul xmlns:py="http://purl.org/kid/ns#"> | |
337 ... <li py:for="item in items">${item}</li> | |
338 ... </ul>''') | |
339 >>> print tmpl.generate(ctxt) | |
340 <ul> | |
341 <li>1</li><li>2</li><li>3</li> | |
342 </ul> | |
343 """ | |
344 __slots__ = ['targets'] | |
345 | |
346 def __init__(self, template, value, pos): | |
347 targets, expr_source = value.split(' in ', 1) | |
348 self.targets = [str(name.strip()) for name in targets.split(',')] | |
349 Directive.__init__(self, template, expr_source, pos) | |
350 | |
351 def __call__(self, stream, ctxt): | |
352 iterable = self.expr.evaluate(ctxt, []) | |
353 if iterable is not None: | |
354 stream = list(stream) | |
355 for item in iter(iterable): | |
356 if len(self.targets) == 1: | |
357 item = [item] | |
358 scope = {} | |
359 for idx, name in enumerate(self.targets): | |
360 scope[name] = item[idx] | |
361 ctxt.push(**scope) | |
362 for event in stream: | |
363 yield event | |
364 ctxt.pop() | |
365 | |
366 def __repr__(self): | |
367 return '<%s "%s in %s">' % (self.__class__.__name__, | |
368 ', '.join(self.targets), self.expr.source) | |
369 | |
370 | |
371 class IfDirective(Directive): | |
372 """Implementation of the `py:if` template directive. | |
373 | |
374 >>> ctxt = Context(foo=True, bar='Hello') | |
375 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
376 ... <b py:if="foo">${bar}</b> | |
377 ... </div>''') | |
378 >>> print tmpl.generate(ctxt) | |
379 <div> | |
380 <b>Hello</b> | |
381 </div> | |
382 """ | |
383 def __call__(self, stream, ctxt): | |
384 if self.expr.evaluate(ctxt): | |
385 return stream | |
386 return [] | |
387 | |
388 | |
389 class MatchDirective(Directive): | |
390 """Implementation of the `py:match` template directive. | |
391 | |
392 >>> ctxt = Context() | |
393 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
394 ... <span py:match="div/greeting"> | |
395 ... Hello ${select('@name')} | |
396 ... </span> | |
397 ... <greeting name="Dude" /> | |
398 ... </div>''') | |
399 >>> print tmpl.generate(ctxt) | |
400 <div> | |
401 <span> | |
402 Hello Dude | |
403 </span> | |
404 </div> | |
405 """ | |
406 __slots__ = ['path', 'stream'] | |
407 | |
408 def __init__(self, template, value, pos): | |
409 Directive.__init__(self, template, None, pos) | |
410 template.filters.append(MatchFilter(value, self._handle_match)) | |
411 self.path = value | |
412 self.stream = [] | |
413 | |
414 def __call__(self, stream, ctxt): | |
415 self.stream = list(stream) | |
416 return [] | |
417 | |
418 def __repr__(self): | |
419 return '<%s "%s">' % (self.__class__.__name__, self.path) | |
420 | |
421 def _handle_match(self, orig_stream, ctxt): | |
422 ctxt.push(select=lambda path: Stream(orig_stream).select(path)) | |
423 for event in self.stream: | |
424 yield event | |
425 ctxt.pop() | |
426 | |
427 | |
428 class ReplaceDirective(Directive): | |
429 """Implementation of the `py:replace` template directive. | |
430 | |
431 >>> ctxt = Context(bar='Bye') | |
432 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
433 ... <span py:replace="bar">Hello</span> | |
434 ... </div>''') | |
435 >>> print tmpl.generate(ctxt) | |
436 <div> | |
437 Bye | |
438 </div> | |
439 | |
440 This directive is equivalent to `py:content` combined with `py:strip`, | |
441 providing a less verbose way to achieve the same effect: | |
442 | |
443 >>> ctxt = Context(bar='Bye') | |
444 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
445 ... <span py:content="bar" py:strip="">Hello</span> | |
446 ... </div>''') | |
447 >>> print tmpl.generate(ctxt) | |
448 <div> | |
449 Bye | |
450 </div> | |
451 """ | |
452 def __call__(self, stream, ctxt): | |
453 kind, data, pos = stream.next() | |
454 yield Stream.EXPR, self.expr, pos | |
455 | |
456 | |
457 class StripDirective(Directive): | |
458 """Implementation of the `py:strip` template directive. | |
459 | |
460 When the value of the `py:strip` attribute evaluates to `True`, the element | |
461 is stripped from the output | |
462 | |
463 >>> ctxt = Context() | |
464 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
465 ... <div py:strip="True"><b>foo</b></div> | |
466 ... </div>''') | |
467 >>> print tmpl.generate(ctxt) | |
468 <div> | |
469 <b>foo</b> | |
470 </div> | |
471 | |
472 On the other hand, when the attribute evaluates to `False`, the element is | |
473 not stripped: | |
474 | |
475 >>> ctxt = Context() | |
476 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
477 ... <div py:strip="False"><b>foo</b></div> | |
478 ... </div>''') | |
479 >>> print tmpl.generate(ctxt) | |
480 <div> | |
481 <div><b>foo</b></div> | |
482 </div> | |
483 | |
484 Leaving the attribute value empty is equivalent to a truth value: | |
485 | |
486 >>> ctxt = Context() | |
487 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
488 ... <div py:strip=""><b>foo</b></div> | |
489 ... </div>''') | |
490 >>> print tmpl.generate(ctxt) | |
491 <div> | |
492 <b>foo</b> | |
493 </div> | |
494 | |
495 This directive is particulary interesting for named template functions or | |
496 match templates that do not generate a top-level element: | |
497 | |
498 >>> ctxt = Context() | |
499 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#"> | |
500 ... <div py:def="echo(what)" py:strip=""> | |
501 ... <b>${what}</b> | |
502 ... </div> | |
503 ... ${echo('foo')} | |
504 ... </div>''') | |
505 >>> print tmpl.generate(ctxt) | |
506 <div> | |
507 <b>foo</b> | |
508 </div> | |
509 """ | |
510 def __call__(self, stream, ctxt): | |
511 if self.expr: | |
512 strip = self.expr.evaluate(ctxt) | |
513 else: | |
514 strip = True | |
515 if strip: | |
516 stream.next() # skip start tag | |
517 # can ignore StopIteration since it will just break from this | |
518 # generator | |
519 previous = stream.next() | |
520 for event in stream: | |
521 yield previous | |
522 previous = event | |
523 else: | |
524 for event in stream: | |
525 yield event | |
526 | |
527 | |
528 class Template(object): | |
529 """Can parse a template and transform it into the corresponding output | |
530 based on context data. | |
531 """ | |
532 NAMESPACE = 'http://purl.org/kid/ns#' | |
533 | |
534 directives = [('def', DefDirective), | |
535 ('match', MatchDirective), | |
536 ('for', ForDirective), | |
537 ('if', IfDirective), | |
538 ('replace', ReplaceDirective), | |
539 ('content', ContentDirective), | |
540 ('attrs', AttrsDirective), | |
541 ('strip', StripDirective)] | |
542 _dir_by_name = dict(directives) | |
543 _dir_order = [directive[1] for directive in directives] | |
544 | |
545 def __init__(self, source, filename=None): | |
546 """Initialize a template from either a string or a file-like object.""" | |
547 if isinstance(source, basestring): | |
548 self.source = StringIO(source) | |
549 else: | |
550 self.source = source | |
551 self.filename = filename or '<string>' | |
552 | |
553 self.pre_filters = [EvalFilter()] | |
554 self.filters = [] | |
555 self.post_filters = [WhitespaceFilter()] | |
556 self.parse() | |
557 | |
558 def __repr__(self): | |
559 return '<%s "%s">' % (self.__class__.__name__, | |
560 os.path.basename(self.filename)) | |
561 | |
562 def parse(self): | |
563 """Parse the template. | |
564 | |
565 The parsing stage parses the XML template and constructs a list of | |
566 directives that will be executed in the render stage. The input is | |
567 split up into literal output (markup that does not depend on the | |
568 context data) and actual directives (commands or variable | |
569 substitution). | |
570 """ | |
571 stream = [] # list of events of the "compiled" template | |
572 dirmap = {} # temporary mapping of directives to elements | |
573 ns_prefix = {} | |
574 depth = 0 | |
575 | |
576 for kind, data, pos in XMLParser(self.source): | |
577 | |
578 if kind is Stream.START_NS: | |
579 # Strip out the namespace declaration for template directives | |
580 prefix, uri = data | |
581 if uri == self.NAMESPACE: | |
582 ns_prefix[prefix] = uri | |
583 else: | |
584 stream.append((kind, data, pos)) | |
585 | |
586 elif kind is Stream.END_NS: | |
587 if data in ns_prefix: | |
588 del ns_prefix[data] | |
589 else: | |
590 stream.append((kind, data, pos)) | |
591 | |
592 elif kind is Stream.START: | |
593 # Record any directive attributes in start tags | |
594 tag, attrib = data | |
595 directives = [] | |
596 new_attrib = [] | |
597 for name, value in attrib: | |
598 if name.namespace == self.NAMESPACE: | |
599 cls = self._dir_by_name.get(name.localname) | |
600 if cls is None: | |
601 raise BadDirectiveError(name, self.filename, pos[0]) | |
602 else: | |
603 directives.append(cls(self, value, pos)) | |
604 else: | |
605 value = list(self._interpolate(value, *pos)) | |
606 new_attrib.append((name, value)) | |
607 if directives: | |
608 directives.sort(lambda a, b: cmp(self._dir_order.index(a.__class__), | |
609 self._dir_order.index(b.__class__))) | |
610 dirmap[(depth, tag)] = (directives, len(stream)) | |
611 | |
612 stream.append((kind, (tag, Attributes(new_attrib)), pos)) | |
613 depth += 1 | |
614 | |
615 elif kind is Stream.END: | |
616 depth -= 1 | |
617 stream.append((kind, data, pos)) | |
618 | |
619 # If there have have directive attributes with the corresponding | |
620 # start tag, move the events inbetween into a "subprogram" | |
621 if (depth, data) in dirmap: | |
622 directives, start_offset = dirmap.pop((depth, data)) | |
623 substream = stream[start_offset:] | |
624 stream[start_offset:] = [(Stream.SUB, | |
625 (directives, substream), pos)] | |
626 | |
627 elif kind is Stream.TEXT: | |
628 for kind, data, pos in self._interpolate(data, *pos): | |
629 stream.append((kind, data, pos)) | |
630 | |
631 else: | |
632 stream.append((kind, data, pos)) | |
633 | |
634 self.stream = stream | |
635 | |
636 def generate(self, ctxt): | |
637 """Transform the template based on the given context data.""" | |
638 | |
639 def _transform(stream): | |
640 # Apply pre and runtime filters | |
641 for filter_ in chain(self.pre_filters, self.filters): | |
642 stream = filter_(iter(stream), ctxt) | |
643 | |
644 try: | |
645 for kind, data, pos in stream: | |
646 | |
647 if kind is Stream.SUB: | |
648 # This event is a list of directives and a list of | |
649 # nested events to which those directives should be | |
650 # applied | |
651 directives, substream = data | |
652 directives.reverse() | |
653 for directive in directives: | |
654 substream = directive(iter(substream), ctxt) | |
655 for event in _transform(iter(substream)): | |
656 yield event | |
657 | |
658 else: | |
659 yield kind, data, pos | |
660 except SyntaxError, err: | |
661 raise TemplateSyntaxError(err, self.filename, pos[0], | |
662 pos[1] + (err.offset or 0)) | |
663 | |
664 stream = _transform(self.stream) | |
665 | |
666 # Apply post-filters | |
667 for filter_ in self.post_filters: | |
668 stream = filter_(iter(stream), ctxt) | |
669 | |
670 return Stream(stream) | |
671 | |
672 _FULL_EXPR_RE = re.compile(r'(?<!\$)\$\{(.+?)\}') | |
673 _SHORT_EXPR_RE = re.compile(r'(?<!\$)\$([a-zA-Z][a-zA-Z0-9_\.]*)') | |
674 | |
675 def _interpolate(cls, text, lineno=-1, offset=-1): | |
676 """Parse the given string and extract expressions. | |
677 | |
678 This method returns a list containing both literal text and `Expression` | |
679 objects. | |
680 | |
681 @param text: the text to parse | |
682 @param lineno: the line number at which the text was found (optional) | |
683 @param offset: the column number at which the text starts in the source | |
684 (optional) | |
685 """ | |
686 patterns = [cls._FULL_EXPR_RE, cls._SHORT_EXPR_RE] | |
687 def _interpolate(text): | |
688 for idx, group in enumerate(patterns.pop(0).split(text)): | |
689 if idx % 2: | |
690 yield Stream.EXPR, Expression(group), (lineno, offset) | |
691 elif group: | |
692 if patterns: | |
693 for result in _interpolate(group): | |
694 yield result | |
695 else: | |
696 yield Stream.TEXT, group.replace('$$', '$'), \ | |
697 (lineno, offset) | |
698 return _interpolate(text) | |
699 _interpolate = classmethod(_interpolate) | |
700 | |
701 | |
702 class TemplateLoader(object): | |
703 """Responsible for loading templates from files on the specified search | |
704 path. | |
705 | |
706 >>> import tempfile | |
707 >>> fd, path = tempfile.mkstemp(suffix='.html', prefix='template') | |
708 >>> os.write(fd, '<p>$var</p>') | |
709 11 | |
710 >>> os.close(fd) | |
711 | |
712 The template loader accepts a list of directory paths that are then used | |
713 when searching for template files, in the given order: | |
714 | |
715 >>> loader = TemplateLoader([os.path.dirname(path)]) | |
716 | |
717 The `load()` method first checks the template cache whether the requested | |
718 template has already been loaded. If not, it attempts to locate the | |
719 template file, and returns the corresponding `Template` object: | |
720 | |
721 >>> template = loader.load(os.path.basename(path)) | |
722 >>> isinstance(template, Template) | |
723 True | |
724 | |
725 Template instances are cached: requesting a template with the same name | |
726 results in the same instance being returned: | |
727 | |
728 >>> loader.load(os.path.basename(path)) is template | |
729 True | |
730 """ | |
731 def __init__(self, search_path=None, auto_reload=False): | |
732 """Create the template laoder. | |
733 | |
734 @param search_path: a list of absolute path names that should be | |
735 searched for template files | |
736 @param auto_reload: whether to check the last modification time of | |
737 template files, and reload them if they have changed | |
738 """ | |
739 self.search_path = search_path | |
740 if self.search_path is None: | |
741 self.search_path = [] | |
742 self.auto_reload = auto_reload | |
743 self._cache = {} | |
744 self._mtime = {} | |
745 | |
746 def load(self, filename): | |
747 """Load the template with the given name. | |
748 | |
749 This method searches the search path trying to locate a template | |
750 matching the given name. If no such template is found, a | |
751 `TemplateNotFound` exception is raised. Otherwise, a `Template` object | |
752 representing the requested template is returned. | |
753 | |
754 Template searches are cached to avoid having to parse the same template | |
755 file more than once. Thus, subsequent calls of this method with the | |
756 same template file name will return the same `Template` object. | |
757 | |
758 @param filename: the relative path of the template file to load | |
759 """ | |
760 filename = os.path.normpath(filename) | |
761 try: | |
762 tmpl = self._cache[filename] | |
763 if not self.auto_reload or \ | |
764 os.path.getmtime(tmpl.filename) == self._mtime[filename]: | |
765 return tmpl | |
766 except KeyError: | |
767 pass | |
768 for dirname in self.search_path: | |
769 filepath = os.path.join(dirname, filename) | |
770 try: | |
771 fileobj = file(filepath, 'rt') | |
772 try: | |
773 tmpl = Template(fileobj, filename=filepath) | |
774 tmpl.pre_filters.append(IncludeFilter(self)) | |
775 finally: | |
776 fileobj.close() | |
777 self._cache[filename] = tmpl | |
778 self._mtime[filename] = os.path.getmtime(filepath) | |
779 return tmpl | |
780 except IOError: | |
781 continue | |
782 raise TemplateNotFound(filename, self.search_path) |