Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 359
arinte Avatar asked Apr 06 '11 19:04

arinte


2 Answers

This should work too.

{% extends "layout.html" %}
{% block body %}
{{ data|safe }}
{% endblock %}
like image 94
Philip Southam Avatar answered Oct 08 '22 01:10

Philip Southam


Instead of data=Markup(feedItem.html).unescape(), you should be using data=Markup(feedItem.html). 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, using unescape() here produces a string/unicode object instead of a Markup object, which keeps Jinja2 from recognizing that the field contains html that needs escaping. This defeats Jinja2's automatic escaping ability (that's the purpose of the Markup class!) I also forces your future template maintainers to remember that this field requires manual escaping, which clutters the template code with extra calls.

like image 28
ʇsәɹoɈ Avatar answered Oct 08 '22 00:10

ʇsәɹoɈ