mschout / perl-text-template

Expand template text with embedded Perl
13 stars 6 forks source link

T::T::Preprocess, &pp called only once, $_ contains entire template [rt.cpan.org #31560] #6

Closed mschout closed 3 years ago

mschout commented 6 years ago

https://rt.cpan.org/Ticket/Display.html?id=31560

As tested, the code ref given to the PREPROCESSOR option is called only 
once, at which time $_ contains the entire template code.

According to the docs:

The preprocessor subroutine will be called repeatedly, once for each 
program fragment. The program fragment will be in $_. The subroutine 
should modify the contents of $_ and return. Text::Template::Preprocess 
will then execute contents of $_ and insert the result into the 
appropriate part of the template.

Distribution: Debian Linux (Etch), Perl v5.8.0 built for i686-linux-
thread-multi

Test results:

$ perl -w test_frag2
got the whole thing

Form start

joel

Some stuff

48

Some more stuff

20000

End of stuff
fragments counted: 1

Test code: 

#!/usr/bin/env perl 
use 5.008;
use warnings;
use Text::Template::Preprocess; 

my $count = 0;; 
my $template = Text::Template::Preprocess->new(
        TYPE => 'STRING',  
        SOURCE => &template,
);
#($name,$age,$income) = qw( joel 48 20000 ); # ??? XX

my $hash = { name => 'joel', age => 48, income => 20000};
my $text = $template->fill_in(
        HASH => $hash,
        PREPROCESSOR => \&preprocess,

);
print $text;
print "fragments counted: $count\n";

sub preprocess { ++$count, $_ eq &template and print "got the whole 
thing\n"; };

sub template { <<'TEMPLATE'};

Form start

{ $name }

Some stuff

{ $age  }

Some more stuff

{ $income }

End of stuff
TEMPLATE
mschout commented 6 years ago

I am using version 1.44 of Text::Template.

mschout commented 6 years ago

Hi again.

What I am trying to do is to use preprocessing magic so that if if a lone bare word appeared in a template { grammar } it will be substituted for the contents of file ./grammar to or the data from a script ./emit_grammar.

The preprocessor checks for this, and rewrites 'grammar' into '$grammar', sets $grammar to the value, pulling the data into the form.

mschout commented 6 years ago

As far as I can tell, the way it behaves is the way MJD intended it to.

Given this has been in production for so long at this point, I'm reluctant to change the way preprocess works at this point.

-- Regards, Michael Schout