1. Home
  2. Computing & Technology
  3. Perl

Perl Module HTML::Template
How to separate HTML from your Perl logic with the HTML::Template Perl module.

From About.com

By keeping your design - HTML, CSS, Javascript - separate from your Perl code, you will save yourself headaches later. Nothing is more frustrating than sorting through a huge application with embedded HTML in print statements. HTML::Template solves this problem by letting you create the HTML in template files and keep them far, far away from your Perl programming.

First, like all non-standard Perl modules, you will need to install HTML::Template from CPAN, and then you can include it at the top of your Perl programs with the use statement:

use HTML::Template;
Before we can get to the Perl part of our program, we'll need to create a template to use in it. A template is a plain, old HTML file, but when we save it, we'll call it my_page.tmpl:
<html>
<head><title>My Template Page</title></head>
<body>
<h1>My Template Page</h1>
<p>Hello, <TMPL_VAR NAME=USERNAME>, this is a template.</p>
</body>
</html>
Now we're ready to use this template in our Perl scripts by pointing it at the file:
my $tpl = HTML::Template->new(filename => 'my_page.tmpl');
Then we can mark the template tags that we want to replace with our data (TMPL_VAR NAME) and fill it in via the script:
$tpl->param(USERNAME => 'About.com User');
And finally print the HTML header and the page itself:
print "Content-Type: text/html\n\n", $tpl->output;
Module Links:
  1. HTML::Template on CPAN
  2. HTML::Template Documentation
  3. Sam Tregar
More Perl Quick Tips
Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Packages & Modules
  6. Perl Module HTML::Template - How to separate HTML from your Perl logic with the HTML::Template Perl module.

©2009 About.com, a part of The New York Times Company.

All rights reserved.