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?';
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.
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.
精彩评论