I’m trying to render a string into a javascript ( which usually works fine for me ) here’s my code
HTML:
THE USER NAME IS : {{name}} has added app {{has_added_app}}
JAVA SCRIPT:
<script>
<!--
var userName = {{name}}
The html version works the javascript fails when I have tried the same rendering in javascript before and it worked.
Comes out when you view the HTML source as:
Which is an obvious mistake: missing quotes. But, simply putting quotes around it:
isn’t good enough for the general case. What if the string contains a quote character, or a backslash, or a newline? Best case, your app falls over. Worst case, cross-site-scripting security hole. What’s more a
&or<character in the name won’t come through properly either, as Django autoescape will probably assume it’s in a non-CDATA HTML context and inappropriately &-escape them.Use the
escapejsfilter instead:Alternatively use a JSON encoder to turn any basic datatype into JavaScript literal format, not just string. There’s json in the standard library from 2.6, but note this doesn’t escape the
<character in strings, so for injecting code into a script element you’d have to escape that manually to prevent a</script>sequence ending the CDATA element prematurely.