2017-04-08 121 views
2

我试图读取2个html文件,并在python中找到另一个,但我收到此错误:*** KeyError:'font-family'将html字符串替换为另一个html字符串

*** KeyError: '    font-family' 

这是我的代码:

with open ("/.../email-template.html", "r") as myfile: 
     html_content=myfile.read().replace("\n", "") 

with open ("/.../product_info.html", "r") as myfile: 
     product_info=myfile.read().replace("\n", "") 

html_content.format(products=product_info) 

这是电子邮件template.html应该被替换的那部分:

... 
<table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" align="center" width="100%" style="max-width: 600px;"> 

       {{products}} 

       <!-- Clear Spacer : BEGIN --> 
       <tr> 
        <td height="40" style="font-size: 0; line-height: 0;"> 
         &nbsp; 
        </td> 
       </tr> 
... 

我怎样才能解决这个问题?

+0

错误来自CSS:字符串= “{{0}} {字体家庭:无衬线}” 字符串=的String.Format( “foo” 的) –

回答

2

给定的模板不适用于str.format(其中{...}用于格式化)。它看起来像Django模板或Jinja模板(考虑它使用{{...}}进行替换)。

使用神社:

with open (".../email-template.html", "r") as myfile: 
    html_content = myfile.read() # removed `replace` to preserve newline 

with open (".../product_info.html", "r") as myfile: 
    product_info = myfile.read().replace("\n", "") 

import jinja2 
formatted = jinja2.Template(html_content).render(products=product_info)