Commits

Sylvain Hellegouarch committed 6dcf2d1

added mako templating recipe

  • Participants
  • Parent commits 758ddd5

Comments (0)

Files changed (4)

web/templating/mako_templating/__init__.py

+# -*- coding: utf-8 -*-
+import os.path
+import cherrypy
+
+class Root(object):
+    @cherrypy.expose
+    def index(self):
+        return {'msg': 'Hello world!'}
+        
+if __name__ == '__main__':
+    # Register the Mako plugin
+    from makoplugin import MakoTemplatePlugin
+    MakoTemplatePlugin(cherrypy.engine, base_dir=os.getcwd()).subscribe()
+
+    # Register the Mako tool
+    from makotool import MakoTool
+    cherrypy.tools.template = MakoTool()
+
+    # We must disable the encode tool because it
+    # transforms our dictionary into a list which
+    # won't be consumed by the mako tool
+    cherrypy.quickstart(Root(), '', {'/': {'tools.template.on': True,
+                                           'tools.template.template': 'index.html',
+                                           'tools.encode.on': False}})

web/templating/mako_templating/index.html

+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15">
+<title></title>
+</head>
+<body>
+${msg}
+</body>
+</html>

web/templating/mako_templating/makoplugin.py

+# -*- coding: utf-8 -*-
+import tempfile
+
+import cherrypy
+from cherrypy.process import plugins
+from mako.lookup import TemplateLookup
+
+__all__ = ['MakoTemplatePlugin']
+
+class MakoTemplatePlugin(plugins.SimplePlugin):
+    """A WSPBus plugin that manages Mako templates"""
+
+    def __init__(self, bus, base_dir=None, base_cache_dir=None, 
+                 collection_size=50, encoding='utf-8'):
+        plugins.SimplePlugin.__init__(self, bus)
+        self.base_dir = base_dir
+        self.base_cache_dir = base_cache_dir or tempfile.gettempdir()
+        self.encoding = encoding
+        self.collection_size = collection_size
+        self.lookup = None
+
+    def start(self):
+        """
+        Called when the engine starts. It will create a template lookup
+        instance used whenever a template needs to be rendered.
+        """
+        self.bus.log('Setting up Mako resources')
+        self.lookup = TemplateLookup(directories=self.base_dir,
+                                     module_directory=self.base_cache_dir,
+                                     input_encoding=self.encoding,
+                                     output_encoding=self.encoding,
+                                     collection_size=self.collection_size)
+        self.bus.subscribe("lookup-template", self.get_template)
+
+    def stop(self):
+        """
+        Called when the engine stops. Cleans ip resources used
+        by the mako engine.
+        """
+        self.bus.log('Freeing up Mako resources')
+        self.bus.unsubscribe("lookup-template", self.get_template)
+        self.lookup = None
+
+    def get_template(self, name):
+        """
+        Returns Mako's template by name.
+
+        Used as follow:
+        >>> template = cherrypy.engine.publish('lookup-template', 'index.html').pop()
+        """
+        return self.lookup.get_template(name)
+        

web/templating/mako_templating/makotool.py

+# -*- coding: utf-8 -*-
+import cherrypy
+from mako import exceptions
+from mako.template import Template
+
+__all__ = ['MakoTool']
+
+class MakoTool(cherrypy.Tool):
+    def __init__(self):
+        cherrypy.Tool.__init__(self, 'before_finalize',
+                               self._render,
+                               priority=10)
+        
+    def _render(self, template=None, debug=False):
+        """
+        Applied once your page handler has been called. It
+        looks up the template from the various template directories
+        defined in the mako plugin then renders it with
+        whatever dictionary the page handler returned.
+        """
+        if cherrypy.response.status > 399:
+            return
+
+        # retrieve the data returned by the handler
+        data = cherrypy.response.body or {}
+        template = cherrypy.engine.publish("lookup-template", template).pop()
+
+        print data, template
+        if template and isinstance(data, dict):
+            # dump the template using the dictionary
+            if debug:
+                try:
+                    cherrypy.response.body = template.render(**data)
+                except:
+                    cherrypy.response.body = exceptions.html_error_template().render()
+            else:
+                cherrypy.response.body = template.render(**data)