Jinja2 转义除 img、b 等之外的所有 HTML

发布于 2024-12-28 18:34:10 字数 91 浏览 3 评论 0原文

Jinja2 自动转义所有 HTML 标签,但我不想转义某些标签(例如 imgb 和其他一些标签)。我该怎么做呢?

Jinja2 automatically escapes all HTML tags, but I want to not escape some tags (like img, b, and some others). How can I do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟酒忠诚 2025-01-04 18:34:10

您可以编写自己的过滤器。 scrubber 非常擅长清理 HTML。过滤器需要将返回的字符串包装在 jinja2.Markup 中,以便模板不会重新转义它。

编辑:代码示例

import jinja2
import scrubber

def sanitize_html(text):
    return jinja2.Markup(scrubber.Scrubber().scrub(text))

jinja_env.filters['sanitize_html'] = sanitize_html

You can write your own filter. The scrubber library is pretty good at cleaning up HTML. The filter will need to wrap the returned string in jinja2.Markup so the template will not re-escape it.

Edit: a code example

import jinja2
import scrubber

def sanitize_html(text):
    return jinja2.Markup(scrubber.Scrubber().scrub(text))

jinja_env.filters['sanitize_html'] = sanitize_html
九局 2025-01-04 18:34:10

您需要使用白名单方法解析提交时的输入 - 有几个很好的示例这个问题可行的选项

完成此操作后,您可以标记任何将包含不应使用 safe 过滤器转义的 HTML 的变量:

{{comment|safe}}

You'll want to parse the input on submission using a white list approach - there are several good examples in this question and viable options out there.

Once you have done that, you can mark any variables that will contain HTML that should not be escaped with the safe filter:

{{comment|safe}}
多情癖 2025-01-04 18:34:10

Bleach 库可以做得很好。

例如,假设变量“jinja_env”在范围内:

from bleach import clean
from markupsafe import Markup

def do_clean(text, **kw):
    """Perform clean and return a Markup object to mark the string as safe.
    This prevents Jinja from re-escaping the result."""
    return Markup(clean(text, **kw))

jinja_env.filters['clean'] = do_clean

那么在模板中您可能会有类似的内容:

<p>{{ my_variable|clean(tags=['img', 'b', 'i', 'em', 'strong'], attributes={'img': ['src', 'alt', 'title', 'width', 'height']}) }}</p>

您还可以在属性中使用可调用(而不是列表),从而允许更彻底地验证属性(例如检查src 提供有效的 URL)。文档显示了示例

The Bleach library can do very well.

For example, assuming the variable 'jinja_env' is in scope:

from bleach import clean
from markupsafe import Markup

def do_clean(text, **kw):
    """Perform clean and return a Markup object to mark the string as safe.
    This prevents Jinja from re-escaping the result."""
    return Markup(clean(text, **kw))

jinja_env.filters['clean'] = do_clean

Then in a template you might have something like:

<p>{{ my_variable|clean(tags=['img', 'b', 'i', 'em', 'strong'], attributes={'img': ['src', 'alt', 'title', 'width', 'height']}) }}</p>

You can also use a callable (instead of a list) in the attributes, allowing more thorough validation of the attributes (e.g. checking that src provides a valid URL). Documentation shows an example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文