从文件加载mako模板
我刚接触Python,现在想用Mako模板。
我想把一个HTML文件和另一个HTML文件的模板结合起来。
假设我有这个 index.html
文件:
<html>
<head>
<title>Hello</title>
</head>
<body>
<p>Hello, ${name}!</p>
</body>
</html>
还有这个 name.html
文件:
world
(是的,它里面只有一个“world”这个词)。
我想把 index.html
中的 ${name}
替换成 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
中的文本,但还没找到办法。请问我该怎么做呢?
3 个回答
1
我理解得对吗?你想要做的就是从一个文件里读取内容?如果你想读取完整的内容,可以用下面这种方式(适用于Python 2.5及以上版本):
from __future__ import with_statement
with open(my_file_name, 'r') as fp:
content = fp.read()
注意:在你的.py文件中,from __future__这一行必须是第一行(或者紧跟在内容编码说明之后,这个说明可以放在第一行)
或者你也可以用旧的方法:
fp = open(my_file_name, 'r')
try:
content = fp.read()
finally:
fp.close()
如果你的文件里有非ASCII字符,你还应该看看codecs页面 :-)
然后,基于你的例子,最后的部分可以这样写:
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()
不过我个人更喜欢那种长一点的写法,因为它明确地关闭了文件 :-)
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)
再次感谢。
2
return mytemplate.render(name=open(<path-to-file>).read())
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。