Python 2.7 读取模板并返回带替换的新文件
我现在把数据加载到一个变量里(下面叫做'数据'),然后读取我的模板文件,把里面的%s替换成'数据'里的变量。下面是我在本地服务器上读取页面、替换内容、写入新页面并显示的代码:
def main
contents = makePage('varibletest.html', (data['Address'], data['Admin'], data['City'], data['ContractNo'], data['DealStatus'], data['Dealer'], data['Finance'], data['FinanceNumber'], data['First'], data['Last'], data['Message'], data['Notes'], data['Result'], data['SoldDate'], data['State'], data['Zip'])) # process input into a page
browseLocal(contents, 'Z:/xampp/htdocs/', 'SmartFormTest{}.php'.format((data['ContractNo']))) # display page
def fileToStr(fileName):
"""Return a string containing the contents of the named file."""
fin = open(fileName);
contents = fin.read();
fin.close()
return contents
def makePage(templateFileName, substitutions):
"""Returns a string with substitutions into a format string taken
from the named file. The single parameter substitutions must be in
a format usable in the format operation: a single data item, a
dictionary, or an explicit tuple."""
pageTemplate = fileToStr(templateFileName)
return pageTemplate % substitutions
def strToFile(text, savefile):
"""Write a file with the given name and the given text."""
output = file(savefile,"w")
output.write(text)
output.close()
def browseLocal(webpageText, path, filename):
"""Start your webbrowser on a local file containing the text."""
savefile = path + filename
strToFile(webpageText, savefile)
import webbrowser
b = webbrowser
b.open('192.168.1.254:1337/' + filename)
main()
这是我的模板文件(里面有一些搞笑的内容,说明我尝试了很多方法来让它工作):
%s
%s
%s
%s
%s
%s
%s.format(Address)
%s.format(data['Address'])
%s[2]
%s(2)
%s{2]
%s
%s
%s
%s
%s
当新页面打开时,所有变量都是按顺序排列的。我需要能够在多个地方插入,比如说地址。
提前谢谢你的帮助!
编辑 --
这是我新的代码,包含了解决方案:
def main()
fin = open('DotFormatTemplate.html')
contents = fin.read();
output = contents.format(**data)
print output
main()
模板文件:
I live at
Address: {Address}
希望这能让某人的生活变得更简单,就像对我一样!
1 个回答
9
使用 string.format
的简单模板
通过 string.format
方法来渲染简单模板的常见方式如下:
data = {"Address": "Home sweet home", "Admin": "James Bond", "City": "London"}
template = """
I live at
Address: {Address}
in City of: {City}
and my admin is: {Admin}
"""
print template.format(**data)
输出结果是:
I live at
Address: Home sweet home
in City of: London
and my admin is: James Bond
这里的 **data
是用来把所有的 data
关键字和相关的值传递给这个函数。
使用 Jinja2 处理复杂模板
string.format
很好,因为它是 Python 标准库的一部分。不过,当你需要处理更复杂的数据结构,比如列表和其他可迭代对象时,string.format
就显得有些力不从心了,或者需要一步一步地构建输出,这样会让你的模板变得过于复杂。
还有很多其他的模板库,我最喜欢的是 jinja2
:
$ pip install jinja2
然后我们可以这样玩:
>>> from jinja2 import Template
>>> jdata = {'Name': 'Jan', 'Hobbies': ['Python', 'collecting principles', 'DATEX II']}
>>> templstr = """
... My name is {{ Name }} and my Hobbies are:
...
... {% for hobby in Hobbies %}
... - {{ hobby }}
... {% endfor %}
... """
>>> templ = Template(templstr)
>>> print templ.render(jdata)
My name is Jan and my Hobbies are:
- Python
- collecting principles
- DATEX II
使用 jinja2
时,不需要调用 templ.render(**jdata)
,不过这样的调用也是可以的。
总结
在这两种情况下,提供的解决方案还有很多其他功能,只需阅读文档,享受其中的乐趣。