generating javascript string in python

3.3k views Asked by At

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?';
2

There are 2 answers

6
Jochen Ritzel On BEST ANSWER

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.

0
Alex Martelli On

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.