我正在尝试读取 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;">
</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)
关于python - *** key 错误 : 'font-family' on replacing a html string into another html string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289156/