[英]How to pass a string with slashes from view to template?
Why does the below code gives me 为什么下面的代码给了我
SyntaxError: unexpected token: ':'
SyntaxError:意外令牌:':'
in the browser's console whenever test
view is called? 每当调用
test
视图时,在浏览器的控制台中?
Is it because the JavaScripts sees the text after slashes in the URL as commented lines? 是因为JavaScripts将URL中的斜杠后的文本视为注释行吗?
How do I fix that? 我该如何解决这个问题?
The view: 风景:
def test(request):
context = {
'url': 'https://www.google.com',
}
return render(request, 'explorer/test.html', context)
The template test.html
: 模板
test.html
:
<script>
var url = {{ url }}
console.log(url)
</script>
这是一个字符串,你只需要把它放在引号中。
var url = "{{ url }}";
Probably the safest way to tackle this is to encode it as a JSON blob, and then use the safe
template filter to make sure that Django does not escape the string, like: 可能最安全的解决方法是将其编码为JSON blob,然后使用
safe
模板过滤器确保Django不会转义字符串,如:
import json
def test(request):
context = {
'url':
json.dumps('https://www.google.com'
),
}
return render(request, 'explorer/test.html', context)
and then in the template render it like: 然后在模板中渲染它:
<script>
var url = {{ url
|safe }}
console.log(url)
</script>
If for example the string you aim to transfer would contain a quote, etc., we could end up with the string terminating in advance, with json.dumps
, this is avoided, for example: 例如,如果您要转移的字符串将包含引号等,我们最终可能会提前终止字符串,使用
json.dumps
,这是可以避免的,例如:
>>> json.dumps('"To be or not to be"')
'"\\"To be or not to be\\""'
So now we have some guarantees that the output is a valid JavaScript object. 所以现在我们有一些保证输出是一个有效的JavaScript对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.