2014-10-29 28 views
0

因此,我終於可以得到Mako的工作。 至少在控制檯中完成的所有工作。 現在我試圖用我的index.htmlMako來渲染,我得到的只是一個空白頁面。 這就是我所說的模塊:通過在python/cherrypy中渲染的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或者我錯過了什麼?

回答

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> 
+0

這太好了。 我不知道與我的server.py有什麼不同(我會稍後再看),但我會用你作爲基礎,並最終開始處理真實的事情。 謝謝親切! – iBaer 2014-10-30 12:15:14

+0

你能解釋一下,你的例子中索引和直接模塊之間有什麼區別?兩者似乎都這樣做,但我想只有在啓動服務器時才使用「索引」模塊,否? – iBaer 2014-10-30 12:39:18

+0

''TemplateLookup''是一個文件系統查找。你在模板根目錄所在的位置告訴它一次,然後讓它獲得一個模板,比如''lookup.get_template('user/cabinet.html')''。你可以自己做同樣的事情,就像在「直接」方法中一樣,指定完整的模板文件名。我給你鏈接到相關的文檔頁面。花點時間瞭解你的模板引擎是如何工作的。 – saaj 2014-10-30 12:50:09