1

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
  • Is the javascript file rendered through the django instance or some webserver(lighttpd) ? Commented Dec 21, 2009 at 2:59

3 Answers 3

8
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.

Sign up to request clarification or add additional context in comments.

Comments

1

comments for the javascript:

var userName = "{{name}}";

Comments

0

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}}";

1 Comment

It's missing the escapejs filter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.