Mercurial > piecrust2
comparison piecrust/templating/pystacheengine.py @ 185:139179dc7abd
render: Add support for a Mustache template engine.
Add unit tests for the new class.
author | Ludovic Chabant <ludovic@chabant.com> |
---|---|
date | Sun, 04 Jan 2015 14:59:12 -0800 |
parents | |
children | f4b7c8f183a4 |
comparison
equal
deleted
inserted
replaced
184:27d623a241c6 | 185:139179dc7abd |
---|---|
1 import logging | |
2 import pystache | |
3 from piecrust.templating.base import ( | |
4 TemplateEngine, TemplateNotFoundError, TemplatingError) | |
5 | |
6 | |
7 logger = logging.getLogger(__name__) | |
8 | |
9 | |
10 class PystacheTemplateEngine(TemplateEngine): | |
11 ENGINE_NAMES = ['mustache'] | |
12 EXTENSIONS = ['mustache'] | |
13 | |
14 def __init__(self): | |
15 self.renderer = None | |
16 | |
17 def renderString(self, txt, data, filename=None): | |
18 self._ensureLoaded() | |
19 try: | |
20 return self.renderer.render(txt, data) | |
21 except pystache.TemplateNotFoundError as ex: | |
22 raise TemplateNotFoundError() from ex | |
23 except pystache.PystacheError as ex: | |
24 raise TemplatingError(str(ex), filename) from ex | |
25 | |
26 def renderFile(self, paths, data): | |
27 self._ensureLoaded() | |
28 tpl = None | |
29 logger.debug("Looking for template: %s" % paths) | |
30 for p in paths: | |
31 if not p.endswith('.mustache'): | |
32 raise TemplatingError( | |
33 "The Mustache template engine only accepts template " | |
34 "filenames with a `.mustache` extension. Got: %s" % | |
35 p) | |
36 name = p[:-9] # strip `.mustache` | |
37 try: | |
38 tpl = self.renderer.load_template(name) | |
39 except Exception as ex: | |
40 print(p, ex) | |
41 pass | |
42 | |
43 if tpl is None: | |
44 raise TemplateNotFoundError() | |
45 | |
46 try: | |
47 return self.renderer.render(tpl, data) | |
48 except pystache.PystacheError as ex: | |
49 raise TemplatingError(str(ex)) from ex | |
50 | |
51 def _ensureLoaded(self): | |
52 if self.renderer: | |
53 return | |
54 | |
55 self.renderer = pystache.Renderer( | |
56 search_dirs=self.app.templates_dirs) | |
57 |