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


Question

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
23
4/6/2011 7:55:36 PM

Accepted Answer

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.

12
11/10/2018 1:39:43 AM

This should work too.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon