package Template::Recall; use 5.008001; use strict; use warnings; use base qw(Template::Recall::Base); our $VERSION='0.11'; sub new { my $class = shift; my $self = {}; my ( %h ) = @_; # Set default values $self->{'is_file_template'} = 0; $self->{'template_flavor'} = qr/html$|htm$/i; $self->{'template_secpat'} = qr/\[\s*=+\s*\w+\s*=+\s*\]/; # Section pattern $self->{'secpat_delims'} = [ '\[\s*=+\s*', '\s*=+\s*\]' ]; # Section delimiters $self->{'delims'} = [ '\[\'', '\'\]' ]; bless( $self, $class ); # Compile flavor, if there is one $self->{'template_flavor'} = $h{'flavor'} if defined( $h{'flavor'} ); # User defines section pattern $self->{'template_secpat'} = qr/$h{'secpat'}/ if defined( $h{'secpat'} ); # Section: User sets 'no delimiters' $self->{'secpat_delims'} = undef if defined($h{'secpat_delims'}) and !ref($h{'secpat_delims'}); # Section: User specifies delimiters $self->{'secpat_delims'} = [ @{ $h{'secpat_delims'} } ] if defined($h{'secpat_delims'}) and ref($h{'secpat_delims'}); # User sets 'no delimiters' $self->{'delims'} = undef if defined($h{'delims'}) and !ref($h{'delims'}); # User specifies delimiters $self->{'delims'} = [ @{ $h{'delims'} } ] if defined($h{'delims'}) and ref($h{'delims'}); # Check the path $self->{'template_path'} = '.' if ( not defined($h{'template_path'}) or !-e $h{'template_path'} ); # Default is local dir # User supplied the template from a string if ( defined($h{'template_str'}) ) { $self->{'template_str'} = $h{'template_str'}; $self->init_template_str(); return $self; } # Single file template: if ( defined($h{'template_path'} ) and -f $h{'template_path'} ) { $self->{'template_path'} = $h{'template_path'}; $self->{'is_file_template'} = 1; # true $self->init_file_template(); return $self; } elsif ( defined($h{'template_path'}) and -d $h{'template_path'} ) { # It's a directory $self->{'template_path'} = $h{'template_path'}; } $self->{'template_path'} =~ s/\\$|\/$//g; # Remove last slash $self->{'template_path'} =~ s/\\/\//g; # All forward slashes # Get all the template files in the given directory opendir(DIR, $self->{'template_path'}) || die "Can't open $self->{'template_path'} $!"; $self->{'template_files'} = [ map { "$self->{'template_path'}/$_" } grep { /$self->{'template_flavor'}/ && -f "$self->{'template_path'}/$_" } readdir(DIR) ]; closedir(DIR); return $self; } # new() sub render { my ( $self, $tpattern, $href ) = @_; # Parameter checks my $np = @_; if ($np < 2) { return "Incorrect number of parameters: $np"; } return "Error: must pass reference to hash\n" if defined($href) and not ref($href); # Single file template handling if ( $self->{'is_file_template'} and ref($href) ) { return render_file($self, $tpattern, $href) } elsif ( $self->{'is_file_template'} ) { # No tags to replace return render_file($self, $tpattern); } # Multiple file template handling # It's preloaded: if ( defined($self->{'preloaded'}{$tpattern}) ) { return $self->SUPER::render( $self->{'preloaded'}{$tpattern}, $href, $self->{'delims'} ); } # Load template file from disk # Does file exist at our location? my $file; for( @{ $self->{'template_files'} } ) { $file = $_ and last if /$tpattern/; } # If we've found it, render it if (defined($file)) { my $t; open(F, $file) or die "Couldn't open $file $!"; while() { $t .= $_; } close(F); return $self->SUPER::render( $t, $href, $self->{'delims'} ); } } # render() # Handles rendering when template is stored in single, sectioned template file sub render_file { my ( $self, $tpattern, $hash_ref ) = @_; my $retval; # Handle section pattern delimiters if they are defined if ( ref($self->{'secpat_delims'}) ) { $tpattern = ${$self->{'secpat_delims'}}[0] . $tpattern . ${$self->{'secpat_delims'}}[1]; } my @template_secs = @{ $self->{'template_secs'} }; for ( my $i=0; $i<$#template_secs; $i++ ) { if ( $template_secs[$i] =~ /$tpattern/ ) { return $template_secs[$i+1] if ( not ref($hash_ref) ); # Return template untouched $retval = $template_secs[$i+1]; # Make copy -- necessary return $self->SUPER::render( $retval, $hash_ref, $self->{'delims'} ); } } return; } # render_file() # Preload template in memory (template sections in multiple files only) sub preload { my ($self, $tpattern) = @_; return if not defined($tpattern) or $self->{'is_file_template'} == 1; # Get the appropriate file my $file; for( @{ $self->{'template_files'} } ) { $file = $_ and last if /$tpattern/; } if (defined($file)) { my $t; open(F, $file) or die "Couldn't open $file $!"; while() { $t .= $_; } close(F); $self->{'preloaded'}{$tpattern} = $t; } return; } # preload() # Remove template from memory (multiple file templates only) sub unload { my ($self, $tpattern) = @_; delete $self->{'preloaded'}{$tpattern}; } # Load the single file template into array of sections sub init_file_template { my $self = shift; my $t; open(F, $self->{'template_path'}) or die "Couldn't open $self->{'template_path'} $!"; while() { $t .= $_; } close(F); $self->{'template_secs'} = [ split( /($self->{'template_secpat'})/, $t ) ]; } # init_file_template() # Handle template passed by user as string sub init_template_str { my $self = shift; $self->{'template_secs'} = [ split( /($self->{'template_secpat'})/, $self->{'template_str'} ) ]; shift(@{$self->{'template_secs'}}); $self->{'is_file_template'} = 1; # render_file() will process this } 1; __END__ =head1 NAME Template::Recall - "Reverse callback" templating system =head1 SYNOPSIS use Template::Recall; # Load template sections from file my $tr = Template::Recall->new( template_path => '/path/to/template/sections' ); # Or, use single file, with sections marked # my $tr = Template::Recall->new( template_path => '/path/to/template_file.html' ); my @prods = ( 'soda,sugary goodness,$.99', 'energy drink,jittery goodness,$1.99', 'green tea,wholesome goodness,$1.59' ); $tr->render('header'); # Load template into memory $tr->preload('prodrow'); for (@prods) { my %h; my @a = split(/,/, $_); $h{'product'} = $a[0]; $h{'description'} = $a[1]; $h{'price'} = $a[2]; print $tr->render('prodrow', \%h); } # Remove template from memory $tr->unload('prodrows'); print $tr->render('footer'); =head1 DESCRIPTION Template::Recall works using what I call a "reverse callback" approach. A "callback" templating system (i.e. Mason, Apache::ASP) generally includes template markup and code in the same file. The template "calls" out to the code where needed. Template::Recall works in reverse. Rather than inserting code inside the template, the template remains separate, but broken into sections. The sections are called from within the code at the appropriate times. A template section is merely a file on disk (or a "marked" section in a single file). For instance, 'prodrow' above (actually F in the template directory), might look like [' product '] [' description '] ['price'] The C method is used to "call" back to the template sections. Simply create a hash of name/value pairs that represent the template tags you wish to replace, and pass a reference of it along with the template section, i.e. $tr->render('prodrow', \%h); =head1 METHODS =head3 C $path ] [, flavor =E $template_flavor] [, secpat =E $section_pattern ] [, delims =E ['opening', 'closing' ] ] )> Instantiates the object. If you do not specify C, it will assume templates are in the directory that the script lives in. If C points to a file rather than a directory, it loads all the template sections from this file. The file must be sectioned using the "section pattern", which can be adjusted via the C parameter. C is a pattern to specify what type of template to load. This is C by default, which picks up HTML file extensions. You could set it to C, for instance, to get *.xml files. C, by default, is C<[\s*=+\s*\w+\s*=+\s*]/>. So if you put all your template sections in one file, the way Template::Recall knows where to get the sections is via this pattern, e.g. [ ==================== header ==================== ] Untitled [ ==================== prodrow ==================== ] [==================== footer ==================== ]
[' product '] [' description '] [' price ']
You may set C to any pattern you wish. Note that if you use delimiters (i.e. opening and closing symbols) for the section pattern, you will also need to set the C parameter to those delimiters. So if you had set C to that above, you would need also need to set C [ '[\s*=+\s*', '\s*=+\s*]' ]>. If you decide to not use delimiters, and use something like C qr/MYTEMPLATE_SECTION_\w+/>, then you must set C 'no'>. The default delimeters for variables in Template::Recall are C<['> (opening) and C<']> (closing). This tells Template::Recall that C<[' price ']> is different from "price" in the same template, e.g. What is the price? It's [' price '] You can change C by passing a two element array to C representing the opening and closing delimiters, such as C [ 'E%', '%E' ]>. If you don't want to use delimiters at all, simply set C 'none'>. The C parameter allows you to pass in a string that contains the template data, instead of reading it from disk: C $str )> For example, this enables you to store templates in the C<__DATA__> section of the calling script =head3 C You must specify C<$template_pattern>, which tells C what template "section" to load. C<$reference_to_hash> is optional. Sometimes you just want to return a template section without any variables. Usually, C<$reference_to_hash> will be used, and C iterates through the hash, replacing the F found in the template with the F associated to F. A reference was chosen for efficiency. The hash may be large, so either pass it using a backslash like in the synopsis, or do something like C<$hash_ref = { 'name' =E 'value' }> and pass C<$hash_ref>. =head3 C In the loop over C<@prods> in the synopsis, the 'prodrow' template is being accessed multiple times. If the section is stored in a file, i.e. F, you have to read from the disk every time C is called. C allows you to load a template section file into memory. Then, every time C is called, it pulls the template from memory rather than disk. This does not work for single file templates, since they are already loaded into memory. =head3 C When you are finished with the template, free up the memory. =head1 AUTHOR James Robson Einfo F arbingersys F comE =head1 SEE ALSO http://perl.apache.org/docs/tutorials/tmpl/comparison/comparison.html