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

标签 python python-2.7

我正在尝试读取 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)

关于python - *** key 错误 : 'font-family' on replacing a html string into another html string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289156/

相关文章:

python - 如何在 argparse 中将可选位置参数与 nargs ='*' 参数一起使用?

python - 为什么 id 函数对整数和 float 的行为不同?

python - Python如何判断一个数字是否用科学计数法表示?

python - 如何在 QTextEdit PYQT 中按下按钮时突出显示和更改行选择

python - 网站加载时如何检查django项目中的用户IP?

Python + uwsgi - 多处理和共享应用程序状态

javascript - 如何创建根据另一个下拉菜单的答案出现的下拉菜单

python - 如何将 StringIO 与 imghdr 结合使用来确定图像是否有效

python - 使用 float 为 Python RNG 播种是否安全?

python - 已安装六个 1.4.1,但在 mac OS sierra 中 set( ['OpenSSL' ]) 需要六个 >=1.5.2