空白页通过在python / cherrypy的Mako模板翻译

时间:2014-10-29 22:54:22

标签: python templates cherrypy mako

所以我终于可以让Mako工作了。 至少在控制台中完成的一切都有效。 现在我尝试使用index.html呈现我的Mako,我得到的只是一个空白页面。 这是我打电话的模块:

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

html是这样的:

<!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>

所以当我调用192.168.0.1:8081/index(这是我运行的本地服务器设置)时,它会启动该功能,但我浏览器中的结果是一个空白页。

我能正确理解Mako还是错过了什么?

1 个答案:

答案 0 :(得分:0)

在基本用法中,一切都很简单,well documented。只需提供正确的引擎路径。

#!/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)

沿着Python文件创建view目录并将以下内容放在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>