Mercurial > genshi > mirror
comparison markup/plugin.py @ 4:49364e784c47 trunk
Added first stab of an implementation of the !TurboGears [http://www.turbogears.org/docs/plugins/template.html plugin API for template engines], and also a !TurboGears-based example using this plugin. Both written by Matt Good.
author | cmlenz |
---|---|
date | Sat, 03 Jun 2006 12:31:58 +0000 |
parents | |
children | b4d17897d053 |
comparison
equal
deleted
inserted
replaced
3:518a8520a6e1 | 4:49364e784c47 |
---|---|
1 # -*- coding: utf-8 -*- | |
2 # | |
3 # Copyright (C) 2006 Mattew Good | |
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 import os | |
15 from pkg_resources import resource_filename | |
16 | |
17 from markup.template import Context, Template, TemplateLoader | |
18 | |
19 | |
20 class TemplateEnginePlugin(object): | |
21 | |
22 def __init__(self, extra_vars_func=None, options=None): | |
23 if options is None: | |
24 options = {} | |
25 # TODO get loader_args from the options dict | |
26 | |
27 self.loader = TemplateLoader(auto_reload=True) | |
28 self.options = options | |
29 self.get_extra_vars = extra_vars_func | |
30 | |
31 def load_template(self, templatename): | |
32 """Find a template specified in python 'dot' notation.""" | |
33 divider = templatename.rfind('.') | |
34 if divider >= 0: | |
35 package = templatename[:divider] | |
36 basename = templatename[divider + 1:] + '.html' | |
37 fullpath = resource_filename(package, basename) | |
38 dirname, templatename = os.path.split(fullpath) | |
39 self.loader.search_path.append(dirname) # Kludge | |
40 | |
41 return self.loader.load(templatename) | |
42 | |
43 def render(self, info, format='html', fragment=False, template=None): | |
44 """Renders the template to a string using the provided info.""" | |
45 return self.transform(info, template).render(method=format) | |
46 | |
47 def transform(self, info, template): | |
48 "Render the output to Elements" | |
49 if not isinstance(template, Template): | |
50 template = self.load_template(template) | |
51 | |
52 data = {} | |
53 if self.get_extra_vars: | |
54 data.update(self.get_extra_vars()) | |
55 data.update(info) | |
56 | |
57 ctxt = Context(**data) | |
58 return template.generate(ctxt) |