我有一个以 Django 作为后端的分析仪表板。 在 Python 中分析数据后,我将发送一个包含名称和显着性的字典。
var things_mentioned = {{entity.name}};
var things_salience = {{entity.salience}};
这会产生一个错误:
语法错误:预期表达式,得到“&”
下面的代码不会产生任何错误并且工作正常:
var things_mentioned = ['noodles', 'food', 'Chinese', 'flavor', 'umami flavor'];
var things_salience = {{entity.salience}};
当我尝试在纯 HTML 页面中查看 {{entity.name}}
值时,它会准确显示此内容
['noodles', 'food', 'Chinese', 'flavor', 'umami flavor'].
此外,我的整个程序中没有一个“&”。
最佳答案
它将尝试对字符串进行 HTML 转义。您可以使用 JavaScript 转义。最安全的方法可能是使用 |json_script
template filter [Django-do] 。因此,您可以将其用作:
{{ entity.name<b>|json_script:"things_mentioned"</b> }}
var things_mentioned = <b>JSON.parse(</b>document.getElementById('things_mentioned').textContent<b>);</b>
关于javascript - 语法错误 : expected expression, 得到 '&' (Django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62458847/