我正在使用 Eleventy 生成博客页面。我的帖子前面有一些 HTML 内容,但无法将其显示为 HTML。当我在模板中引用它时,它会转换为 HTML 字符实体。
这就是帖子前面的内容:
title: test
date: 2024-04-01
headerImage: american_flag_partial.jpg
imageCredit: Photo by <a
href="https://unsplash.com/@timmossholder?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Tim
Mossholder</a> on <a
href="https://unsplash.com/photos/us-a-flag-on-white-and-red-striped-textile-QsX23A3NgMQ?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>
在我的 post.njk 模板中
{% if imageCredit %}{{ imageCredit }}{% endif %}
渲染
Photo by <a href="https://unsplash.com/@timmossholder?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Tim Mossholder</a> on <a href="https://unsplash.com/photos/us-a-flag-on-white-and-red-striped-textile-QsX23A3NgMQ?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>
如何防止字符串被转换为HTML字符实体?我已经阅读了 11ty 文档,但我还没有发现如何做到这一点。
好吧,如何让 HTML 通过 Nunjucks 设置的块帮助我弄清楚了。是 nunjucks 逃离了 HTML。
改变
{% if imageCredit %}{{ imageCredit }}{% endif %}
到
{% if imageCredit %}{{ imageCredit | safe }}{% endif %}
在我的 post.njk 模板中解决了这个问题。
可以在这个问题中找到更多信息,Stop nunjucks from escapeing HTML。
来自 nunjucks 手册
Safe
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
我认为安全会使其安全,而不是...不安全....