Jinja2 转义除 img、b 等之外的所有 HTML
Jinja2 自动转义所有 HTML 标签,但我不想转义某些标签(例如 img
、b
和其他一些标签)。我该怎么做呢?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以编写自己的过滤器。 scrubber 库 非常擅长清理 HTML。过滤器需要将返回的字符串包装在 jinja2.Markup 中,以便模板不会重新转义它。
编辑:代码示例
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
您需要使用白名单方法解析提交时的输入 - 有几个很好的示例这个问题和可行的选项。
完成此操作后,您可以标记任何将包含不应使用
safe
过滤器转义的 HTML 的变量: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:Bleach 库可以做得很好。
例如,假设变量“jinja_env”在范围内:
那么在模板中您可能会有类似的内容:
您还可以在属性中使用可调用(而不是列表),从而允许更彻底地验证属性(例如检查src 提供有效的 URL)。文档显示了示例。
The Bleach library can do very well.
For example, assuming the variable 'jinja_env' is in scope:
Then in a template you might have something like:
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.