2

我是 python 新手,目前正在尝试使用 mako 模板。我希望能够获取一个 html 文件并从另一个 html 文件中添加一个模板。假设我得到了这个index.html文件:

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

这个name.html文件:

world

(是的,它里面只有世界这个词)。我希望将${name}inindex.html替换为name.html文件的内容。name.html通过使用以下代码在渲染方法中说明名称是什么,我已经能够在没有文件的情况下执行此操作:

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

这对于较大的文本显然没有用。现在我想要的只是简单地从 加载文本name.html,但还没有找到一种方法来做到这一点。我应该尝试什么?

4

3 回答 3

2
return mytemplate.render(name=open(<path-to-file>).read())
于 2010-08-19T12:30:14.273 回答
2

感谢您的回复。
这个想法是使用 mako 框架,因为它会执行缓存等操作并检查文件是否已更新......

这段代码似乎最终可以工作:

@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)

再次感谢。

于 2010-08-19T13:46:02.160 回答
1

我是否正确理解您,您想要的只是从文件中读取内容?如果您想阅读完整的内容,请使用以下内容(Python >= 2.5):

from __future__ import with_statement

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

注意: from __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)

您可以在官方文档中找到有关文件对象的更多详细信息 :-)

还有一个快捷版:

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

但我个人更喜欢带有显式关闭的长版本:-)

于 2010-08-19T12:29:08.077 回答