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
Description: Digital signature
