Skip to content

Instantly share code, notes, and snippets.

@kazeburo
Created November 11, 2010 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazeburo/672234 to your computer and use it in GitHub Desktop.
Save kazeburo/672234 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use Text::Xslate;
use Plack::Request;
my $bs = '\\';
my %e = (
q!\\! => $bs,
q!"! => 'x22',
q!'! => 'x27',
q!/! => '/',
q!<! => 'x3c',
q!>! => 'x3e',
q!&! => 'x26',
"\x0D" => "r",
"\x0A" => "n",
);
sub escape_js {
my ($text) = @_;
$text =~ s!([\\"'/<>&]|\x0D|\x0A)!${bs}$e{$1}!g;
return $text;
}
my $tx = Text::Xslate->new(
syntax => 'TTerse',
function => {
js => sub {
escape_js(@_);
},
js_raw => sub {
Text::Xslate::mark_raw(escape_js(@_));
}
}
);
sub {
my $env = shift;
my $req = Plack::Request->new($env);
my $foo = $req->param('foo') // q!&foo"bar'<b>baz</b>\ / </script>! . qq!\r\nfoo!;
return [
200,
['Content-Type'=>'text/html'],
[$tx->render_string(<<'EOF',
<html>
<body>
<script>
// test | html | js
var foo='[% test | html | js_raw %]';
document.write(foo);
</script>
<br />
<!-- test | js -->
<a onclick="alert('[% test | js %]')">alert</a>
</body>
</html>
EOF
{ test => $foo }
)]
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment