in reply to Parse template into data structure

Without getting too complicated - here are the basics.

use Template; { package MyStash; use base qw(Template::Stash); sub undefined { my $self = shift; my @ident = shift; print "(".join("|",@ident).")\n"; if (@ident > 1) { return ''; } elsif ($ident[0] eq 'adjective') { return 'red'; } elsif ($ident[0] eq 'noun') { return 'fox'; } elsif ($ident[0] eq 'verb') { return 'jumped'; } else { return ''; } } } my $stash = MyStash->new; my $string = "The [% adjective %] [% noun %] [% verb %] over the river +.\n"; Template->new(STASH => $stash)->process(\$string);


my @a=qw(random brilliant braindead); print $a[rand(@a)];

Replies are listed 'Best First'.
Re^2: Parse template into data structure
by Rhandom (Curate) on Nov 07, 2006 at 16:02 UTC
    And if you'd rather use CGI::Ex::Template (which is Template::Toolkit compatible template wise) you could use the following code (I'd use CGI::Ex::Template personally - but that might be because I'm intimately familiar with it :)).

    use CGI::Ex::Template; my $cet = CGI::Ex::Template->new( UNDEFINED_GET => sub { my $self = shift; my $ident = shift; print "(".join("|",@$ident).")\n"; if (@$ident > 2) { return ''; } elsif ($ident->[0] eq 'adjective') { return 'red'; } elsif ($ident->[0] eq 'noun') { return 'fox'; } elsif ($ident->[0] eq 'verb') { return 'jumped'; } else { return ''; } }, ); my $string = "The [% adjective %] [% noun %] [% verb %] over the river +.\n"; $cet->process(\$string);


    my @a=qw(random brilliant braindead); print $a[rand(@a)];
      UNDEFINED_GET in this package appears to be able to do what I had in mind. I will have to take some time to play with it a bit. Thank you.