Skip to main content
 首页 » 编程设计

python之*** 键错误 : 'font-family' on replacing a html string into another html string

2024年10月01日9insus

我正在尝试读取 2 个 html 文件,并在 python 中一个到另一个,但出现此错误:

*** 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) 

这是 email-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> 
... 

我该如何解决这个问题?

请您参考如下方法:

给定的模板不适用于 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)