[Catalyst] I18N with quotation marks

Jose Luis Martinez jlmartinez-lists-catalyst at capside.com
Fri Jul 3 10:27:05 GMT 2009

Ton Voon escribió:
> For javascript in <script> blocks, you should use single quotes for the 
> string value and pass through an escape_js filter, eg:
> <script>
> var string = '[% c.loc("May have single quotes or \ in it") | escape_js 
> %]';
> </script>

Instead of forcing yourself to use single quoted strings in javascript, 
you can escape single quotes AND double quotes :)

alert('I\'m a string with \\ and lots of \"things\"');
alert("I\'m a string with \\ and lots of \"things\"");

return the same output.

And to make it more solid...

You would expect that:

alert('I\'m a </script> string');

would show you a nice alert. You're wrong :) At least FF3 and IE fail. I 
suppose that it's very normal (because the browser's parser understands 
nothing about the string context of the javascript, and thinks the 
<script> tag ends just in the middle of your script.

The solution is as easy as to "hide" the script tag from the parser.
alert('I\'m a <\/script> string');

Note: I don't know if it's better to escape all "/", or all "</" or just 
"</script>" instances in the string. Any thoughts?

 > $Template::Stash::SCALAR_OPS->{escape_js} = sub {
 >    my $s = shift;
 >    $s =~ s/\\/\\\\/g;
 >    $s =~ s/'/\\'/g;
 >    return $s;
 > };

Maybe it's more efficient to do this in one pass?
$s =~ s/(\\|'|"|\/)/\\$1/g;

Just my 2 cents,

Jose Luis Martinez
jlmartinez at capside.com

More information about the Catalyst mailing list