问题
i'm developing Flask App. I want to transfer simple json from the app.py to the html page.
This is the relevant code at app.py:
jsonArr = [{"type": "circle", "label": "New York"},
{"type": "circle", "label": "New York"}]
return render_template('demo.html', foo=42, imgs=jsonArr)
This is how I receive it it javascript script inside the html:
<script>
console.log("HI")
var foo = {{ foo }}
console.log(foo)
var images = {{ imgs }}
console.log(images)
foo is received correctly (I see the printing on the console when I remove the lines for receiving imgs)
But imgs makes error: Uncaught SyntaxError: Unexpected token &
This is what I see in the chrome browser sources:
var images = [['circle', 'New York'], ['triangle', 'Amsterdam']]
This is the html declerations:
<!DOCTYPE html>
<html class="no-js" lang="en">
I've tried adding/removing <meta charset="UTF-8"> but it didn't work.
What am I missing? Thanks
回答1:
In order to avoid cross-site-scripting attacks, flask automatically escapes HTML sequences. If you want to avoid this, you can directly tell Flask you know what you're doing:
https://stackoverflow.com/a/3266740/3029173
from flask import Markup
value = Markup('<strong>The HTML String</strong>')
However!! This is risky from a security perspective. If you have any user data that can end up in the JSON, you need to consider another approach.
You would need to sanitize the JSON so a user doesn't come along with a string of </script><script>do bad things here</script>
回答2:
You should have a separate route with the data in JSON format.
from flask import jsonify
jsonArr = [{"type": "circle", "label": "New York"},
{"type": "circle", "label": "New York"}]
return jsonify(jsonArr)
来源:https://stackoverflow.com/questions/49572810/string-passed-as-34-from-python-flask-to-html-page