trivk96 trivk96 - 5 months ago 20
HTML Question

Pass JSON from flask to template and decode html entity

So I have been stuck on this for a while. I have a MongoDB that i query and return as JSON.

I do this by:

bson.json_utils.dumps(list(all_exams.find(query))


I then pass this into a flask template variable to use in an inline js script in HTML.

<div id="results">
<table id="results-table">
</table>
<p>
{{results_json}}
</p>

</div>


<script type="text/javascript" charset="utf-8">
$('#results-table').dynatable({
dataset: {
records: {{results_json}}
}
});
</script>


The problem is that in the script, the JSON cannot be parsed by denotable properly because it contains
&#34;
That is the entity value for a double quote but shouldn't it not appear like that if i inspect the source code. Shouldn't the html page display it as an
"
. This only happens in the script section. Not in the
<p>
tag (that prints out all
&#34;
as
"
).

What am I misunderstanding?

Answer

To avoid XSS attacks, flask and other template languages escape values by default: it converts " into the HTML entity so that the browser reads it as text to be displayed for humans rather than the part of the HTML syntax (e.g. <a href="...">). This happens in all tags: inside the <p> tag you see the quote in your browser but the source code is still the entity.

To tell flask to not escape stuff, use {{results_json | safe}}. That's you asserting that the value is safe, not telling flask to make it safe (which is what it was doing before).