tags:

views:

205

answers:

3

hi, 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.

+1  A: 

comments for the javascript:

var userName = "{{name}}";
teepark
A: 

Remember that Django templates are purely textual: they don't "know" that you're creating Javascript. You need to include the quotes that Javascript needs around a string literal:

var userName = "{{name}}";
Ned Batchelder
It's missing the escapejs filter
Peter Bengtsson
+8  A: 
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.

bobince