从文件加载mako模板

2024-05-19 08:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这个name.html文件:

^{pr2}$

(是的,里面只有世界这个词)。 我希望将index.html中的${name}替换为name.html文件的内容。 我可以在不使用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加载文本,但是还没有找到一种方法。我该试试什么?在


Tags: 文件方法name文本模板helloindextitle
3条回答

感谢您的回复。
我们的想法是使用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)

再次感谢。在

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

from __future__ import with_statement

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

注意:from\uu future_uu行必须是.py文件中的第一行(或可以放在第一行的内容编码规范之后)

或者旧方法:

^{pr2}$

如果您的文件包含非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()

但我个人更喜欢有明确结尾的长版本:-)

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

相关问题 更多 >

    热门问题