Forums

Passing JSON string to rendered template in Flask

I am having an issue passing a valid JSON string using the render_template() function in Flask. I remember that I encountered this problem on my test environment but the same solution there isn't working here. To explain more, I am attempting to pass a GeoJSON string that I have created with Python processes to a template that renders this GeoJSON string in OpenLayers, a JavaScript library. The problem is that instead of quotation characters, &#34 characters show up when I pass the string to my template. The function call for the render template is:

return render_template('rect.html',string=json)

In which json is a valid GeoJSON string, and string is the template variable in the HTML file. The specific part of the HTML template in question is here:

fc = {{string|tojson}}

Curiously, I can print the string in another template that is pure HTML:

<!DOCTYPE html>
<html lang="en">

  <body>
    {{string}}
  </body>
</html>

When I render the template, the source page looks like so:

<!DOCTYPE html>
<html lang="en">

  <body>
    {&#34;crs&#34;: {&#34;type&#34;: &#34;name&#34;, &#34;properties&#34;: {&#34;name&#34;: &#34;epsg:3857&#34;}}, &#34;type&#34;: &#34;Polygon&#34;, &#34;coordinates&#34;: [[[2531347.9951568414, 4759840.927412586], [2531296.7040879447, 4759862.399097161], [2531219.267172451, 4759692.783624653], [2531271.194558173, 4759669.538568315], [2531347.9951568414, 4759840.927412586]]]}
  </body>
</html>

So the weird characters are showing up here as well.

Those are encoded versions of the characters. Use the safe filter like this:

fc = {{string|tojson|safe}}