Text::Templet Use Scenario

If your web site is hosted on Apache server, you can configure it so that you can use Text::Templet and Perl with the ease of PHP. No more CGI/Perl scripts! The reason PHP is easy to use is that in the simplest case it is just an HTML page. You can create as many as you want, you don’t need to worry about setting permissions, and it’s very easy to debug because you get a meaningful response right in the browser instead of a 500 Server Error and digging error details from server logs.

Apache server has a mechanism that allows you to create custom content handlers – you can make Apache launch a specific program or script when a file with a particular extension is requested, and send its output to the browser. Best of all, this feature can be configured from the .htaccess file, and thus is available at many shared web hosting accounts.

To make this work, we need three things: a content handler script, a folder with template files containing your application, and an .htaccess file in the root of that folder.

Let’s start with the handler code:

use Text::Templet;

my $pagetext;
local(*PAGE, $/);
open (PAGE, $ENV{'PATH_TRANSLATED'})     || die "can't open file $_[0]: $!";
my @fstat = stat(PAGE);
read(PAGE,$pagetext,$fstat[7]); # $fstat[7] is the size of the file
close PAGE;
print "Content-type: text/html\r\n\r\n";


if ( $@ )
my $errortext = $@;
print "<body><div>Error:</div><div><pre>$errortext</pre></div><div></body>";

The handler is very simple – it loads the requested file passed to it by Apache in PATH_TRANSLATED environment variable, sends a standard HTTP header and passes the contents of the file to Text::Templet for processing. Any errors in the template will be reported through the $@ variable and displayed in the browser.

.htaccess file looks like this:

AddHandler pa-handler .pa
Action pa-handler /cgi-bin/pa.pl
DirectoryIndex index.pa

The following assumptions are made: the handler code above is saved in /cgi-bin/pa.pl, with executable permission set, and our template files have .pa extension. In addition, index.pa will be called when only directory is requested.

Finally, a simple template to get you started:

use vars qw($hello);
$hello = "Hello, World!";
Perl Application says: $hello

I’ve put all these pieces together to make it easy for you to try it out. Download pa.tar.gz or pa.zip, extract pa.pl and Text/Templet.pm from cgi-bin into cgi-bin folder on your web server, then create a new folder somewhere in your html document tree and extract .htaccess and hello.pa into it. Verify that pa.pl has execute permission set and open http://yourserver/folder/hello.pa . Click here to see this example code running on my web host.

You can use this example as a starting point and add features such as authentication and security. You can also put your Perl code in modules and reference them from your templates.

Leave a Reply