[Templates-cvs] cvs commit: TT3/examples scanner.pl
cvs@template-toolkit.org
cvs@template-toolkit.org
Mon, 02 Feb 2004 10:03:53 +0000
cvs 04/02/02 10:03:52
Added: examples scanner.pl
Log:
* added example showing use of the scanner and different tags
Revision Changes Path
1.1 TT3/examples/scanner.pl
Index: scanner.pl
===================================================================
#!/usr/bin/perl -w # -*- perl -*-
#
# Perl script written by Andy Wardley. This is free software.
#
use strict;
use warnings;
use lib qw( ../lib ./lib );
use Template::TT3::Handler;
use Template::TT3::Scanner;
use Template::TT3::Generator::Debug;
use Template::TT3::Tag;
# define scanner
my $scanner = Template::TT3::Scanner->new({
tags => [
Template::TT3::Tag->new({ # TODO: should be able to pass hash refs
start => '<$', # and have the scanner auto-vivify
end => '$>', # Tag objects for you
parse => \&dollar_tag,
}),
Template::TT3::Tag->new({
start => '<?',
end => '?>',
parse => \&question_tag,
}),
]
});
# subroutine for parsing <$ ... $> tags
sub dollar_tag {
my ($self, $textref, $handler, $match) = @_;
# YOUR CODE HERE - we're just going to do some simple stuff
# for debugging purposes, like fetching the current location
# and collapsing whitespace
$$textref =~ s/\s+/ /g;
my $locn = $self->location();
# notify the handler of some new content
return $handler->directive( dollar => "at $locn: [$$textref]" )
|| $self->error($handler->error());
}
# subroutine for parsing <? ... ?> tags
sub question_tag {
my ($self, $textref, $handler, $match) = @_;
# YOUR CODE HERE - we're just testing - see above
$$textref =~ s/\s+/ /g;
my $locn = $self->location();
# first argument denotes the content type, any other args can follow
return $handler->directive( question => "at $locn: [$$textref]" )
|| $self->error($handler->error());
}
# read input from __DATA__
local $/ = undef;
my $input = <DATA>;
# define a handler to construct document content
my $handler = Template::TT3::Handler->new();
# scan document
$handler->start();
$scanner->scan($input, $handler) || die $scanner->error();
my $result = $handler->end() || die $handler->error();
# create a generator to display document
my $generator = Template::TT3::Generator::Debug->new({});
# generators );
my $output = $generator->generate($result)
|| die $generator->error();
print "-- input --\n",
$input, "\n",
"-- output --\n",
$output, "\n";
__DATA__
This is some text
before <? to be or not to be ?> after
start <$ money, money, money $> end
tags can <?
span
multiple
lines
and ?> the scanner takes
care of counting
<$
line
numbers
$> for you