Why does the below code gives me
SyntaxError: unexpected token: ':'
in the browser's console whenever test
view is called?
Is it because the JavaScripts sees the text after slashes in the URL as commented lines?
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
:
<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:
import json
def test(request):
context = {
'url': 'https://www.google.com',
}
return render(request, 'explorer/test.html', context)
and then in the template render it like:
<script>
var url = {{ url }}
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('"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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.