Text escaped when I want it to show up as html in Flask/jinja2

烂漫一生 提交于 2019-12-30 01:39:06

问题


I pull a feed from rss and store the data in a appengine db. The rss feed content includes the entire html. So I have this python code:

@app.route("/rssRead")
def pullRss():
    feedItem = db.getFeedItemByName(request.args.get('title',None), request.args.get('key',None))
    return render_template("rss.html", data= Markup(feedItem.html).unescape())

And my html template looks like this:

{% extends "layout.html" %}
{% block body %}
{{ data }}
{% endblock %}

So when I view the page I have the actual html markup being displayed, how do I unescape the html data?


回答1:


You should be using data=Markup(feedItem.html) instead of data=Markup(feedItem.html).unescape(). That will do the right thing and keep your template clean.

Calling unescape() here is pointless (unless feeditem.html contains pre-escaped html, which it probably doesn't). More importantly, it interferes with Jinja2's ability to recognize that the field as html that needs escaping, by producing a string/unicode object instead of a Markup object. You're effectively throwing away Jinja2's ability to handle escaping automatically (that's the purpose of the Markup class!) and instead forcing your future template maintainers to remember that this field requires manual escaping and to clutter the template code with an extra call to do so.




回答2:


This should work too.

{% extends "layout.html" %}
{% block body %}
{{ data|safe }}
{% endblock %}


来源:https://stackoverflow.com/questions/5572225/text-escaped-when-i-want-it-to-show-up-as-html-in-flask-jinja2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!