Created
June 8, 2009 08:15
-
-
Save mala/125699 to your computer and use it in GitHub Desktop.
auto html escape in TT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/perl | |
use strict; | |
use Template; | |
package HTMLString; | |
use strict; | |
use warnings; | |
use overload '""' => \&as_string; | |
use overload "." => \&concat; | |
sub new { | |
my ($klass, $str) = @_; | |
bless \$str, $klass; | |
} | |
sub as_string { | |
my $self = shift; | |
return $$self; | |
} | |
sub concat { | |
my ($self, $other, $reversed) = @_; | |
my $class = ref $self; | |
if ($other) { | |
my $newval = ($reversed) ? $other . $$self : $$self . $other; | |
return bless \$newval, $class; | |
} else { | |
return $self; | |
} | |
} | |
package Template::Stash::EscapeHTML; | |
use strict; | |
use Template::Config; | |
use base ($Template::Config::STASH); | |
our $VERSION = '0.01'; | |
sub get { | |
my($self, @args) = @_; | |
my($var) = $self->SUPER::get(@args); | |
unless (ref($var)) { | |
return html_filter($var); | |
} | |
return $var; | |
} | |
sub html_filter { | |
my $text = shift; | |
for ($text) { | |
s/&/&/g; | |
s/</</g; | |
s/>/>/g; | |
s/"/"/g; | |
} | |
return $text; | |
} | |
package main; | |
use Scalar::Util qw(refaddr); | |
sub html_filter2 { | |
my $text = shift; | |
return $text if (ref $text eq "HTMLString"); | |
for ($text) { | |
s/&/&/g; | |
s/</</g; | |
s/>/>/g; | |
s/"/"/g; | |
} | |
return $text; | |
} | |
my $tmpl = join '', <DATA>; | |
my $tt = Template->new({ | |
STASH => Template::Stash::EscapeHTML->new, | |
FILTERS => { | |
html => \&html_filter2, | |
}, | |
}); | |
my $data = { | |
string => "<b>hoge</b>", | |
escaped_string => esc("<b>hoge</b>"), | |
}; | |
sub esc { | |
return HTMLString->new($_[0]); | |
} | |
$tt->process(\$tmpl, $data) or die $tt->error; | |
__DATA__ | |
<html> | |
[% escaped_string %] | |
aaa | |
[% escaped_string | html %] | |
aaa | |
[% string %] | |
aaa | |
[% string | html %] | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment