#!/usr/bin/perl -T
###################
#
# A fairly simple example of a perl template engine.
# 
# Visiting homegrown.cgi?template=example.txt will process 
# and output that template.  The template may contain expressions
# like [% word %] which will be replaced by the value of 
# any CGI parameters passed in other than "file".
# The template file will be output as text/plain if it ends in .txt, 
# otherwise it'll be text/html.
#
# To try it out, visit
#   homegrown.cgi?template=example.txt&to=Joe&mood=happy&from=Jim
#
# The two most popular versions of modules to do this sort of thing
# are Template Toolkit and HTML::Mason.
#
# Jim Mahoney, September 2004
#
##################
use strict;
use warnings;
$ENV{PATH}='';
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);

# Read all the form parameters into a hash, except 'template'.
my %data;
foreach my $key (param){
  $data{$key} = param($key) unless $key eq 'template';
}

# Read in the text from the template file.
my $template = param('template') || '';
-e $template or die "Oops - couldn't find template file '$template'";
open(INPUT, "< $template") 
  or die "Oops - couldn't open '$template' for reading";
my $text = join('',<INPUT>);
close(INPUT);

# Replace each template tag with the corresponding form data.
$text =~ s{  \[\%     # opening [%
             \s*      # leading optional whitespace
             (\w+)    # word made of at least one word char
             \s*      # trailing optional whitespace
             \%\]     # closing [%
           }{$data{$1}}xg;

# Output the header.
# If the template file ends in .txt, give it type text/plain, 
# otherwise, use the default (text/html).
if ( $template =~ /\.txt$/ ){
  print header( -type => 'text/plain' );
} 
else {
  print header;
}

# Output the template.
print $text;



