Search code examples
pythontemplatescherrypymako

Blank page through Mako template rendering in python / cherrypy


So it finally seems that I could get Mako to work. At least everything done in the console works. Now I tried to render my index.html with Mako and all I get is a blank page. This is the module I call:

    def index(self):
    mytemplate = Template(
                    filename='index.html'
                )   
    return mytemplate.render()

The html is this:

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="UTF-8" />
</head>
<body>
<p>This is a test!</p>
<p>Hello, my age is ${30 - 2}.</p>
</body>
</html>

So when I call 192.168.0.1:8081/index (this is the local server setup I run) it starts the function, but the result in my browser is a blank page.

Do I understand Mako correctly or did I miss something?


Solution

  • In basic usage everything is quite simple, and well documented. Just provide correct paths to the engine.

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    
    import os
    
    import cherrypy
    from mako.lookup import TemplateLookup
    from mako.template import Template
    
    
    path   = os.path.abspath(os.path.dirname(__file__))
    config = {
      'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080,
        'server.thread_pool' : 8
      }
    }
    
    
    lookup = TemplateLookup(directories=[os.path.join(path, 'view')])
    
    
    class App:
    
      @cherrypy.expose
      def index(self):
        template = lookup.get_template('index.html')
        return template.render(foo = 'bar')
    
      @cherrypy.expose  
      def directly(self):
        template = Template(filename = os.path.join(path, 'view', 'index.html'))
        return template.render(foo = 'bar')
    
    
    
    if __name__ == '__main__':
      cherrypy.quickstart(App(), '/', config)
    

    Along the Python file, create view directory and put the following under index.html.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Title</title>
      <meta charset="UTF-8" />
    </head>
    <body>
      <p>This is a ${foo} test!</p>
      <p>Hello, my age is ${30 - 2}.</p>
    </body>
    </html>