2017-04-08 205 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)