Skip to content

Instantly share code, notes, and snippets.

@mala
Created June 8, 2009 08:15
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 mala/125699 to your computer and use it in GitHub Desktop.
Save mala/125699 to your computer and use it in GitHub Desktop.
auto html escape in TT
#!/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/</&lt;/g;
s/>/&gt;/g;
s/"/&quot;/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/&/&amp;/g;
s/</&lt;/g;
s/>/&gt;/g;
s/"/&quot;/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