Python 如何通过flask消息显示html内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18225713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display html content through flask messages?
提问by naga4ce
I understand that flash()
takes only string and displays that in the redirected page.
I m trying to send html through flash
我知道flash()
只需要字符串并在重定向页面中显示它。我正在尝试通过 flash 发送 html
message = "<h1>Voila! Platform is ready to used</h1>"
flash(message)
return render_template('output.html')
output.html
输出.html
<div class="flashes">
{% for message in get_flashed_messages()%}
{{ message }}
{% endfor %}
</div>
But it is displaying as string <h1>Voila! Platform is ready to used</h1>
is there any way to overcome this.
但它显示为字符串<h1>Voila! Platform is ready to used</h1>
有什么办法可以克服这个问题。
采纳答案by the911s
Where possible, a secure approach is to wrap your string in a Markup object before passing it to the template:
在可能的情况下,一种安全的方法是在将字符串传递给模板之前将其包装在一个 Markup 对象中:
Python code:
蟒蛇代码:
from flask import Markup
message = Markup("<h1>Voila! Platform is ready to used</h1>")
flash(message)
return render_template('output.html')
Jinja2 Template:
Jinja2 模板:
<div class="flashes">
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</div>
Using {{message|safe}}
will work, but also opens up the door for an attacker to inject malicious HTML or Javascript into your page, also known an an XSS attack. More info hereif you're interested.
使用{{message|safe}}
会起作用,但也会为攻击者打开大门,将恶意 HTML 或 Javascript 注入您的页面,也称为 XSS 攻击。如果您有兴趣,请在此处了解更多信息。
回答by Burhan Khalid
Use the safe
filter:
使用safe
过滤器:
<div class="flashes">
{% for message in get_flashed_messages()%}
{{ message|safe }}
{% endfor %}
</div>
回答by Seth IK
FOr cases where you might want to control the css applied depending on the status of message (Success | Error), the following code might be useful
对于您可能希望根据消息的状态(成功 | 错误)控制应用的 css 的情况,以下代码可能有用
{% for category, msg in get_flashed_messages(with_categories=true) %}
<div class="alert {{ category }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{ msg|safe }}
</div>
{% endfor %}
{% 结束为 %}
回答by bertdida
Another way is to call render_template
to the external HTML file and passing that to Markup
class.
另一种方法是调用render_template
外部 HTML 文件并将其传递给Markup
类。
main/routes.py
主要/路线.py
from flask import render_template, flash, Markup
from . import blueprint
@blueprint.route("/user")
def user():
flash(Markup(render_template("templates/user.html", name="John Doe"))
return render_template("templates/home.html")
templates/user.html
模板/用户.html
<h1>User: {{ name }}</h1>