Python 2.7读取模板并返回带有替换的新文件

时间:2014-06-05 16:52:09

标签: python string python-2.7 variable-declaration

我目前正在将数据加载到变量中(在下面显示为'数据'),然后读取我的模板文件并将%s替换为' data'中包含的变量。这是我的页面读取,替换,编写然后在本地服务器代码上显示新页面:

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 个答案:

答案 0 :(得分:4)

使用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),但此类通话也可以。

结论

上面的示例应该为您提供初步想法,可以使用模板做什么以及如何使用它们。

在这两种情况下,给定的解决方案提供了更多功能,只需阅读文档并享受它。