var userName = {{name}}
Comes out when you view the HTML source as:
var userName = Bob
Which is an obvious mistake: missing quotes. But, simply putting quotes around it:
var userName = '{{name}}';
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 escapejs
filter instead:
var userName = '{{name|escapejs}}';
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.