呈现的 HTML 模板中的双引号格式问题 - Python FastAPI

Double Quotes Formatting Issue in Rendered HTML Template - Python FastAPI

提问人:iakigarci 提问时间:11/13/2023 更新时间:11/13/2023 访问量:20

问:

我在 Python FastAPI 微服务中呈现的 HTML 模板中遇到了双引号的格式问题。HTML 模板存储在名为“templates”的文件夹中,并在 {{}} 表达式中包含变量,这些变量被 Python 代码替换。目标是呈现此模板并将其作为 HTML 字符串返回。

但是,当返回 HTML 时,格式与预期不同。HTML 包含带反斜杠的双引号,导致间距问题。我在下面分享了一个问题的简化示例:

返回的 HTML 带有“\:

<span class=\"text_base text-9\">+34 642521273</span>
                </p>
<p class=\"spacer\"></p>\n
<!-- ... (more HTML) ... -->

Python 代码:

async def __create_file__(
        self,
        input: InputData,
        contract_adapted,
        event_contract,
        draft: bool,
    ):
        env_template = Environment(
            loader=FileSystemLoader("/"),
            enable_async=True,
        )

        template = env_template.get_template(os.getenv(contract_adapted.template))
        render_template = await template.render_async(contract_adapted.data)

        pdf_task = asyncio.create_task(
            self.create_pdf(input, contract_adapted, event_contract, render_template)
        )

        if draft:
            render_template = render_template.replace('\\"', '"').replace("\\n", "")

            with open(
                os.getenv(contract_adapted.styles), "r", encoding="utf-8"
            ) as css_file:
                css_content = css_file.read().replace("\n", "")

            render_template_with_style = (
                f"<style>{css_content}</style>{render_template}"
            )

            return render_template_with_style

        await pdf_task
        return pdf_task.result()

问题:

当 HTML 以草稿模式返回时,由于双引号被反斜杠转义,因此其格式很差。

预期结果:

我想返回一个格式良好的 HTML 字符串,在双引号之前没有额外的反斜杠。

蟒蛇 HTML jinja2 fastapi

评论


答: 暂无答案