Search code examples
javascriptpythoncheetah

generating javascript string in python


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

Solution

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