使用 Flask/Jinja2 将 HTML 传递到模板
我正在为 Flask 和 SQLAlchemy 构建一个管理员,我想使用 render_template
将不同输入的 HTML 传递到我的视图。模板框架似乎会自动转义 HTML,因此所有 <"'>
字符都会转换为 HTML 实体。如何禁用它以便 HTML 正确呈现?
I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template
. The templating framework seems to escape the HTML automatically, so all <"'>
characters are converted to HTML entities. How can I disable that so that the HTML renders correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
要在渲染值时关闭自动转义,请使用
|safe
过滤器。仅对您信任的数据执行此操作,因为在不转义的情况下呈现不受信任的数据是跨站点脚本漏洞。
To turn off autoescaping when rendering a value, use the
|safe
filter.Only do this on data you trust, since rendering untrusted data without escaping is a cross-site scripting vulnerability.
MarkupSafe 提供 Jinja 的自动转义行为。您可以导入
Markup
并使用它来声明一个不受代码影响的 HTML 值:将其传递给模板,您不必在其上使用
|safe
过滤器。MarkupSafe provides Jinja's autoescaping behavior. You can import
Markup
and use it to declare a value HTML safe from the code:Pass that to the templates and you don't have to use the
|safe
filter on it.来自 Jinja 文档部分 HTML 转义:
例子:
From the Jinja docs section HTML Escaping:
Example:
当你有很多不需要转义的变量时,你可以使用
autoescape
覆盖 块:When you have a lot of variables that don't need escaping, you can use an
autoescape
override block:为了具体处理换行符,我尝试了多种选择,然后最终解决了这个问题:
这种方法的好处是它与自动转义兼容,让一切都变得美好和安全。它还可以与过滤器结合使用,例如 urlize。
当然,它与 Helge 的答案类似,但不需要宏(而是依赖于 Jinja 的内置
split
函数),也不会添加不必要的
在最后一项之后。For handling line-breaks specifically, I tried a number of options before finally settling for this:
The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.
Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in
split
function) and also doesn't add an unnecesssary<br/>
after the last item.有些人似乎关闭了自动转义,这会带来安全风险来操纵字符串显示。
如果您只想在字符串中插入一些换行符并将换行符转换为
,那么您可以采用 jinja 宏,例如:并在您的 <强>模板只需调用它
Some people seem to turn autoescape off which carries security risks to manipulate the string display.
If you only want to insert some linebreaks into a string and convert the linebreaks into
<br />
, then you could take a jinja macro like:and in your template just call this with
在模板中使用
safe
过滤器,然后使用 您视图中的bleach
库。使用漂白剂,您可以将需要使用的 HTML 标签列入白名单。据我所知,这是最安全的。我尝试了
safe
过滤器和Markup
类,这两种方法都允许我执行不需要的 JavaScript。不太安全!Use the
safe
filter in your template, and then sanitize the HTML with thebleach
library in your view. Using bleach, you can whitelist the HTML tags that you need to use.This is the safest, as far as I know. I tried both the
safe
filter and theMarkup
class, and both ways allowed me to execute unwanted JavaScript. Not very safe!