Use json.dumps instead of qjs and you have a beautiful solution there, and not just for strings.
On Nov 1, 7:42 am, Marius Gedminas <[email protected]> wrote: > On Sun, Oct 31, 2010 at 07:53:46PM -0700, Eric Rasmussen wrote: > > Another option is to load part of it in a <script> tag in the HTML template. > > For instance (using Mako): > > > <script> > > var titles = []; > > % for book in c.books: > > titles[${book.index}] = '${book.title}'; > > This breaks down when book.title contains an apostrophe. > > Also, this doesn't suppress HTML quoting, and IIRC browsers will interpret > things like '&' like a string of 5 characters, not a string of one > character. > > I ended up writing a function to quote javascript string literals: > > def qjs(s): > r"""Quote a string for Javascript. > > >>> print qjs('hi') > 'hi' > >>> print qjs("I'm back!") > 'I\x27m back!' > > """ > s = (s.replace('\\', '\\\\') > .replace('\'', '\\x27') > .replace('"', '\\x22') > .replace('<', '\\x3c') > .replace('>', '\\x3e') > .replace('&', '\\x26')) > return literal("'%s'") % s > > I use it like this: > > <script> > titles[${book.index}] = ${book.title|qjs}; > </script> > > or > > <a href="#" onclick="some_function(${param|qjs})">Do something</a> > > which explains why I need to be so careful with ampersands and quotes. > > I've no idea how portable this way of quoting is across browsers. > > > How does everyone else handle this? Maybe we can get something up on the > > wiki about the best way to handle it in Pylons. > > Go for it! > > Consider my qjs to be public domain, if that helps. > > Marius Gedminas > -- > "What's the name of the new OO COBOL -- an equivalent of C++?" > "ADD 1 TO COBOL GIVING COBOL" > > signature.asc > < 1KViewDownload -- You received this message because you are subscribed to the Google Groups "pylons-discuss" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/pylons-discuss?hl=en.
