Skip to content

Instantly share code, notes, and snippets.

@wchristian
Created January 1, 2011 20:52
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 wchristian/762001 to your computer and use it in GitHub Desktop.
Save wchristian/762001 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
package Template::AutoFilter;
use base 'Template';
use lib '..';
use Template::AutoFilter::Parser;
sub new {
my $class = shift;
my $params = defined($_[0]) && ref($_[0]) eq 'HASH' ? shift : {@_};
$params->{FILTERS}{none} ||= sub { $_[0] };
$params->{PARSER} ||= Template::AutoFilter::Parser->new( $params );
return $class->SUPER::new( $params );
}
1;
#!/usr/bin/perl
use strict;
use warnings;
package autofilter;
use lib 'lib';
use lib '../lib';
use Test::Most;
run_tests();
done_testing;
exit;
sub tests {(
{
name => 'plain text remains unfiltered',
tmpl => '<a>',
expect => '<a>',
},
{
name => 'excluded tokens remain unfiltered',
tmpl => '[% test | none %]',
expect => '<a>',
},
{
name => 'unfiltered tokens get filtered',
tmpl => '[% test %]',
expect => '&lt;a&gt;',
},
{
name => 'specifically filtered tokens get filtered',
tmpl => '[% test | html %]',
expect => '&lt;a&gt;',
},
{
name => 'other filters are applied without the autofilter',
tmpl => '[% test | upper %]',
expect => '<A>',
},
)}
sub run_tests {
use_ok "Template::AutoFilter";
run_test($_) for tests();
return;
}
sub run_test {
my ( $test ) = @_;
$test->{params} ||= {};
my $tt = Template::AutoFilter->new( $test->{params} );
my $out;
my $res = $tt->process( \$test->{tmpl}, { test => '<a>' }, \$out );
subtest $test->{name} => sub {
cmp_deeply( [ $tt->error, $res ], [ '', 1 ], 'no template errors' );
is( $out, $test->{expect}, 'output is correct' );
};
return;
}
use strict;
use warnings;
package Template::AutoFilter::Parser;
use base 'Template::Parser';
sub new {
my ( $class, $params ) = @_;
my $self = $class->SUPER::new( $params );
$self->{AUTO_FILTER} = $params->{AUTO_FILTER} || 'html';
return $self;
}
sub split_text {
my ( $self, @args ) = @_;
my $tokens = $self->SUPER::split_text( @args ) or return;
for my $token ( @{$tokens} ) {
next if !ref $token;
my %fields = @{$token->[2]};
next if $fields{FILTER};
push @{$token->[2]}, qw( FILTER | IDENT ), $self->{AUTO_FILTER};
}
return $tokens;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment