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 :)

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

return the same output.

And to make it more solid...

You would expect that:

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

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.
<script>
alert('I\'m a <\/script> string');
</script>

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
[email protected]


_______________________________________________
List: [email protected]
Listinfo: http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
Searchable archive: http://www.mail-archive.com/[email protected]/
Dev site: http://dev.catalyst.perl.org/

Reply via email to