从文件加载 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
文件的情况下完成此操作,方法是在渲染方法中使用以下代码说明 name 是什么:
@route(':filename')
def static_file(filename):
mylookup = TemplateLookup(directories=['html'])
mytemplate = mylookup.get_template('hello/index.html')
return mytemplate.render(name='world')
这显然对于较大的文本片段没有用处。现在我想要的只是从 name.html
加载文本,但尚未找到实现此目的的方法。我应该尝试什么?
I'm new to python and currently trying to use mako templating.
I want to be able to take an html file and add a template to it from another html file.
Let's say I got this index.html
file:
<html>
<head>
<title>Hello</title>
</head>
<body>
<p>Hello, ${name}!</p>
</body>
</html>
and this name.html
file:
world
(yes, it just has the word world inside).
I want the ${name}
in index.html
to be replaced with the content of the name.html
file.
I've been able to do this without the name.html
file, by stating in the render method what name is, using the following code:
@route(':filename')
def static_file(filename):
mylookup = TemplateLookup(directories=['html'])
mytemplate = mylookup.get_template('hello/index.html')
return mytemplate.render(name='world')
This is obviously not useful for larger pieces of text. Now all I want is to simply load the text from name.html
, but haven't yet found a way to do this. What should I try?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我是否理解正确,您想要的只是从文件中读取内容?如果您想阅读完整的内容,请使用类似以下内容(Python >= 2.5):
注意: from __future__ 行必须是 .py 文件中的第一行(或紧接在内容之后)可以放在第一行的编码规范)
或者旧方法:
如果您的文件包含非 ascii 字符,您还应该查看编解码器页面:-)
然后,根据您的示例,最后一部分可以查看像这样:
您可以在以下位置找到有关 文件对象 的更多详细信息官方文档:-)
还有一个快捷版本:
但我个人更喜欢带有显式结束的长版本:-)
Did I understand you correctly that all you want is read the content from a file? If you want to read the complete content use something like this (Python >= 2.5):
Note: The from __future__ line has to be the first line in your .py file (or right after the content encoding specification that can be placed in the first line)
Or the old approach:
If your file contains non-ascii characters, you should also take a look at the codecs page :-)
Then, based on your example, the last section could look like this:
You can find more details about the file object in the official documentation :-)
There is also a shortcut version:
But I personally prefer the long version with the explicit closing :-)
谢谢各位的回复。
这个想法是使用 mako 框架,因为它可以执行诸如缓存和检查文件是否已更新之类的操作...
此代码似乎最终可以工作:
再次感谢。
Thanks for the replies.
The idea is to use the mako framework since it does things like cache and check if the file has been updated...
this code seems to eventually work:
Thanks again.