Package turbogears :: Package view :: Module genshisupport

Source Code for Module turbogears.view.genshisupport

 1  """Template support for Genshi template engine. 
 2   
 3  This module implements a sub-class of 
 4  ``genshi.template.plugin.MarkupTemplateEnginePlugin``, to support our extension 
 5  to the Buffet templating API that allows to pass additional template engine 
 6  options as keyword arguments to the ``render()`` method of engines. 
 7   
 8  This is necessary, for example, to allow us to pass different doctypes to 
 9  Genshi when rendering to different XML-based formats, i.e. HTML, XHML, XML, RSS, 
10  etc. or to omit the doctype all together. 
11   
12  """ 
13   
14  from genshi.output import DocType 
15  from genshi.template.plugin import MarkupTemplateEnginePlugin 
16   
17   
18 -class TGGenshiTemplatePlugin(MarkupTemplateEnginePlugin):
19 """Custom Genshi template engine plugin supporting Buffet API extensions.""" 20
21 - def __init__(self, extra_vars_func=None, options=None):
22 default_doctype = options.pop('genshi.default_doctype', None) 23 MarkupTemplateEnginePlugin.__init__(self, extra_vars_func, options) 24 self.default_doctype = default_doctype
25
26 - def render(self, info, format="html", fragment=False, template=None, 27 **options):
28 """Render the template to a string using the provided info.""" 29 kwargs = self._get_render_options(format=format, fragment=fragment, 30 **options) 31 return self.transform(info, template).render(**kwargs)
32
33 - def _get_render_options(self, format=None, fragment=False, **options):
34 """Return options dict for rendering the given format.""" 35 # We do not call the methods of the base-classes here, because they 36 # would screw up the options, so we have to implement their behavior 37 # ourselves. 38 if format is None: 39 format = self.default_format 40 kwargs = {'method': format} 41 if self.default_encoding: 42 kwargs['encoding'] = self.default_encoding 43 doctype = options.pop('doctype', self.default_doctype) 44 kwargs.update(options) 45 if doctype and not fragment: 46 if isinstance(doctype, dict): 47 doctype = doctype.get(format) 48 if doctype: 49 doctype = DocType.get(doctype) 50 if doctype is None: 51 raise ConfigurationError('Unknown doctype %r' % doctype) 52 kwargs['doctype'] = doctype 53 return kwargs
54