2010-08-19 86 views
2

我是python新手,目前正在嘗試使用mako模板。 我希望能夠從另一個html文件中獲取一個html文件並向其中添加一個模板。 比方說,我得到這個index.html文件:從文件加載mako模板

<html> 
<head> 
    <title>Hello</title> 
</head> 
<body>  
    <p>Hello, ${name}!</p> 
</body> 
</html> 

name.html文件:

world 

(是的,它只是裏面的字的世界)。 我想用name.html文件的內容替換index.html中的${name}。 我已經能夠做到這一點沒有name.html文件,通過陳述在Render方法什麼名字,使用下面的代碼:

@route(':filename') 
def static_file(filename):  
    mylookup = TemplateLookup(directories=['html']) 
    mytemplate = mylookup.get_template('hello/index.html') 
    return mytemplate.render(name='world') 

這顯然不適合大塊文本的有用。現在我只想加載name.html中的文本,但還沒有找到辦法做到這一點。我應該嘗試什麼?

回答

1

我的理解是否正確:您要的只是從文件中讀取內容?如果你想閱讀完整內容使用像這樣(的Python> = 2.5):

from __future__ import with_statement 

with open(my_file_name, 'r') as fp: 
    content = fp.read() 

注:的從__future__線必須是在你的.py文件的第一行(或右後可以放置在第一行內容編碼規範)

還是老辦法:

fp = open(my_file_name, 'r') 
try: 
    content = fp.read() 
finally: 
    fp.close() 

如果文件中包含非ASCII字符,你也應該看看編解碼器頁面:-)

然後,根據你的榜樣,最後一節可能是這樣的:

from __future__ import with_statement 

@route(':filename') 
def static_file(filename):  
    mylookup = TemplateLookup(directories=['html']) 
    mytemplate = mylookup.get_template('hello/index.html') 
    content = '' 
    with open('name.html', 'r') as fp: 
     content = fp.read() 
    return mytemplate.render(name=content) 

您可以找到有關的官方文檔中的file object更多細節:-)

還有一個快捷版:

content = open('name.html').read() 

但我個人比較喜歡長版本與明確的收盤:-)

2
return mytemplate.render(name=open(<path-to-file>).read()) 
2

感謝您的回覆。
這個想法是因爲它確實喜歡緩存的東西用灰鯖框架,並檢查文件是否已經更新...

此代碼似乎最終奏效:再次

@route(':filename') 
def static_file(filename):  
    mylookup = TemplateLookup(directories=['.']) 
    mytemplate = mylookup.get_template('index.html') 
    temp = mylookup.get_template('name.html').render() 
    return mytemplate.render(name=temp) 

感謝。