将字符串以&#34的形式从Python Flask传递到HTML页面 [英] String passed as &#34 from Python Flask to HTML Page
问题描述
我正在开发Flask App. 我想将简单的json从app.py转移到html页面.
i'm developing Flask App. I want to transfer simple json from the app.py to the html page.
这是app.py中的相关代码:
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)
这就是我在html内接收它的javascript脚本的方式:
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正确接收(当我删除用于接收img的行时,我在控制台上看到打印内容)
foo is received correctly (I see the printing on the console when I remove the lines for receiving imgs)
但是imgs出错:Uncaught SyntaxError: Unexpected token &
这是我在chrome浏览器源代码中看到的:
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']]
这是html缩图:
<!DOCTYPE html>
<html class="no-js" lang="en">
我尝试添加/删除<meta charset="UTF-8">
,但是没有用.
I've tried adding/removing <meta charset="UTF-8">
but it didn't work.
我想念什么?谢谢
推荐答案
为避免跨站点脚本攻击,flask会自动转义HTML序列.如果您想避免这种情况,可以直接告诉Flask您知道自己在做什么:
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>')
但是!!从安全角度来看,这是有风险的.如果您有任何可以以JSON结尾的用户数据,则需要考虑另一种方法.
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.
您需要清理JSON,以便用户不会附带</script><script>do bad things here</script>
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>
这篇关于将字符串以&#34的形式从Python Flask传递到HTML页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!