Skip to content

@wchristian /AutoFilter.pm
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.