views:

129

answers:

2

i have string stored in python variables, and i am outputting a html that contains javascript, and the i need to create javascript variables.

for ex, in python

title = "What's your name?"

i use Cheetah to generate the html. Cheetah code:

var title = '$title';

how do i escape this correctly so that a correct javascript variable is created? actual html output needed:

var title = 'What\'s your name?';
+3  A: 

You probably want JSON:

import simplejson as sj
print sj.dumps('What\'s your name?') # => '"What\'s your name?"'

Don't generate js with cheetah, there are libraries.

THC4k
this works great! thanks a lot, can you tell what libraries are available that i can use?
kevin
THC4kthanks for this, when I tried this the output works correctly in python. but the actual html output from Cheetah does not have the escape character. do you know what is going on?
kevin
A: 

Either just do title = title.replace("'", "\\'") in Python before the title value gets to Cheetah, or add a custom filter to Cheetah for the purpose and invoke it in the template. Doing it on the Python side of things seems simpler, though.

Alex Martelli