++ed by:

3 PAUSE users
7 non-PAUSE users.

Sam Tregar


HTML::Template - Perl module to use HTML Templates from CGI scripts


First you make a template - this is just a normal HTML file with a few extra tags, the simplest being <TMPL_VAR>

For example, test.tmpl:

  <HEAD><TITLE>Test Template</TITLE>
  My Home Directory is <TMPL_VAR NAME=HOME>
  My Path is set to <TMPL_VAR NAME=PATH>

Now create a small CGI program:

  use HTML::Template;

  # open the html template
  my $template = HTML::Template->new(filename => 'test.tmpl');

  # fill in some parameters
      HOME => $ENV{HOME},
      PATH => $ENV{PATH},

  # send the obligatory Content-Type
  print "Content-Type: text/html\n\n";

  # print the template
  print $template->output;

If all is well in the universe this should show something like this in your browser when visiting the CGI:

My Home Directory is /home/some/directory My Path is set to /bin;/usr/bin


This module attempts to make using HTML templates simple and natural. It extends standard HTML with a few new HTML-esque tags - <TMPL_VAR>, <TMPL_LOOP>, <TMPL_INCLUDE>, <TMPL_IF> and <TMPL_ELSE>. The file written with HTML and these new tags is called a template. It is usually saved separate from your script - possibly even created by someone else! Using this module you fill in the values for the variables, loops and branches declared in the template. This allows you to separate design - the HTML - from the data, which you generate in the Perl script.

This module is licensed under the GPL. See the LICENSE section below for more details.


It is true that there are a number of packages out there to do HTML templates. On the one hand you have things like HTML::Embperl which allows you freely mix Perl with HTML. On the other hand lie home-grown variable substitution solutions. Hopefully the module can find a place between the two.

One advantage of this module over a full HTML::Embperl-esque solution is that it enforces an important divide - design and programming. By limiting the programmer to just using simple variables and loops in the HTML, the template remains accessible to designers and other non-perl people. The use of HTML-esque syntax goes further to make the format understandable to others. In the future this similarity could be used to extend existing HTML editors/analyzers to support HTML::Template.

An advantage of this module over home-grown tag-replacement schemes is the support for loops. In my work I am often called on to produce tables of data in html. Producing them using simplistic HTML templates results in CGIs containing lots of HTML since the HTML itself cannot represent loops. The introduction of loop statements in the HTML simplifies this situation considerably. The designer can layout a single row and the programmer can fill it in as many times as necessary - all they must agree on is the parameter names.

For all that, I think the best thing about this module is that it does just one thing and it does it quickly and carefully. It doesn't try to replace Perl and HTML, it just augments them to interact a little better. And it's pretty fast.

The Tags

Note: even though these tags look like HTML they are a little different in a couple of ways. First, they must appear entirely on one line. Second, they're allowed to "break the rules". Something like:


is not really valid HTML, but it is a perfectly valid use and will work as planned.

The "NAME=" in the tag is optional, although for extensibility's sake I recommend using it. Example - "<TMPL_LOOP LOOP_NAME>" is acceptable.

If you're a fanatic about valid HTML and would like your templates to conform to valid HTML syntax, you may optionally type template tags in the form of HTML comments. This may be of use to HTML authors who would like to validate their templates' HTML syntax prior to HTML::Template processing, or who use DTD-savvy editing tools.


In order to realize a dramatic savings in bandwidth, the standard (non-comment) tags will be used throughout the rest of this documentation.


The <TMPL_VAR> tag is very simple. For each <TMPL_VAR> tag in the template you call $template->param(PARAMETER_NAME => "VALUE"). When the template is output the <TMPL_VAR> is replaced with the VALUE text you specified. If you don't set a parameter it just gets skipped in the output.

Optionally you can use the "ESCAPE=1" option in the tag to indicate that you want the value to be HTML-escaped before being returned from output. This means that the ", <, >, and & characters get translated into &quot;, &lt;, &gt; and &amp; respectively. This is useful when you want to use a TMPL_VAR in a context where those characters would cause trouble. Example:


If you called param() with a value like sam"my you'll get in trouble with HTML's idea of a double-quote. On the other hand, if you use ESCAPE=1, like this:


You'll get what you wanted no matter what value happens to be passed in for param. You can also write ESCAPE="1" and ESCAPE='1'. Substitute for the 1 and you turn off escaping, which is the default anyway.


The <TMPL_LOOP> tag is a bit more complicated. The <TMPL_LOOP> tag allows you to delimit a section of text and give it a name. Inside the <TMPL_LOOP> you place <TMPL_VAR>s. Now you pass to param() a list (an array ref) of parameter assignments (hash refs) - the loop iterates over this list and produces output from the text block for each pass. Unset parameters are skipped. Here's an example:

   In the template:

         Name: <TMPL_VAR NAME=NAME> <P>
         Job: <TMPL_VAR NAME=JOB> <P>

   In the script:

                     { name => 'Sam', job => 'programmer' },
                     { name => 'Steve', job => 'soda jerk' },
   print $template->output();

   The output:

   Name: Sam <P>
   Job: programmer <P>
   Name: Steve <P>
   Job: soda jerk <P>

As you can see above the <TMPL_LOOP> takes a list of variable assignments and then iterates over the loop body producing output.

Often you'll want to generate a <TMPL_LOOP>'s contents programmatically. Here's an example of how this can be done (many other ways are possible!):

   # a couple of arrays of data to put in a loop:
   my @words = qw(I Am Cool);
   my @numbers = qw(1 2 3);

   my @loop_data = ();  # initialize an array to hold your loop

   for (my $x = 0; $x < 3; $x++) {
     my %row_data;  # get a fresh hash for the row data

     # fill in this row
     $row_data{WORD} = $words[$x];
     $row_data{NUMBER} = $numbers[$x];
     # the crucial step - push a reference to this row into the loop!
     push(@loop_data, \%row_data);

   # finally, assign the loop data to the loop param, again with a
   # reference:
   $template->param(THIS_LOOP => \@loop_data);

The above example would work with a template like:

      Word: <TMPL_VAR NAME="WORD"><BR>
      Number: <TMPL_VAR NAME="NUMBER"><P>

It would produce output like:

   Word: I
   Number: 1

   Word: Am
   Number: 2

   Word: Cool
   Number: 3

<TMPL_LOOP>s within <TMPL_LOOP>s are fine and work as you would expect. If the syntax for the param() call has you stumped, here's an example of a param call with one nested loop:

                          { name => 'Bobby',
                            nicknames => [
                                          { name => 'the big bad wolf' }, 
                                          { name => 'He-Man' },

Basically, each <TMPL_LOOP> gets an array reference. Inside the array are any number of hash references. These hashes contain the name=>value pairs for a single pass over the loop template. It is probably in your best interest to build these up programmatically, but that is up to you!

Inside a <TMPL_LOOP>, the only variables that are usable are the ones from the <TMPL_LOOP>. The variables in the outer blocks are not visible within a template loop. For the computer-science geeks among you, a <TMPL_LOOP> introduces a new scope much like a subroutine call.

<TMPL_INCLUDE NAME="filename.tmpl">

This tag includes a template directly into the current template at the point where the tag is found. The included template contents exactly as if its contents were physically included in the master template.

The file specified can be a full path - beginning with a '/'. If it isn't a full path, the path to the enclosing file is tried first. After that the path in the environment variable HTML_TEMPLATE_ROOT is tried next. Next, the "path" new() option is consulted. As a final attempt, the filename is passed to open() directly. See below for more information on HTML_TEMPLATE_ROOT and the "path" option to new().

As a protection against infinitly recursive includes, an arbitary limit of 10 levels deep is imposed. You can alter this limit with the "max_includes" option. See the entry for the "max_includes" option below for more details.


The <TMPL_IF> tag allows you to include or not include a block of the template based on the value of a given parameter name. If the parameter is given a value that is true for Perl - like '1' - then the block is included in the output. If it is not defined, or given a false value - like '0' - then it is skipped. The parameters are specified the same way as with TMPL_VAR.

Example Template:

     Some text that only gets displayed if BOOL is true!

Now if you call $template->param(BOOL => 1) then the above block will be included by output.

<TMPL_IF> </TMPL_IF> blocks can include any valid HTML::Template construct - VARs and LOOPs and other IF/ELSE blocks. Note, however, that intersecting a <TMPL_IF> and a <TMPL_LOOP> is invalid.


WARNING: Much of the benefit of HTML::Template is in decoupling your Perl and HTML. If you introduce numerous cases where you have TMPL_IFs and matching Perl if()s, you will create a maintenance problem in keeping the two synchronized. I suggest you adopt the practice of only using TMPL_IF if you can do so without requiring a matching if() in your Perl code.


You can include an alternate block in your TMPL_IF block by using TMPL_ELSE. NOTE: You still end the block with </TMPL_IF>, not </TMPL_ELSE>!


     Some text that is included only if BOOL is true
     Some text that is included only if BOOL is false


This tag is the opposite of <TMPL_IF>. The block is output if the CONTROL_PARAMETER is set false or not defined. You can use <TMPL_ELSE> with <TMPL_UNLESS> just as you can with <TMPL_IF>.


    Some text that is output only if BOOL is FALSE.
    Some text that is output only if BOOL is TRUE.



Call new() to create a new Template object:

  my $template = HTML::Template->new( filename => 'file.tmpl', 
                                      option => 'value' 

You must call new() with at least one name => value pair specifying how to access the template text. You can use "filename => 'file.tmpl'" to specify a filename to be opened as the template. Alternately you can use:

  my $t = HTML::Template->new( scalarref => $ref_to_template_text, 
                               option => 'value' 


  my $t = HTML::Template->new( arrayref => $ref_to_array_of_lines , 
                               option => 'value' 

These initialize the template from in-memory resources. These are mostly of use internally for the module - in almost every case you'll want to use the filename parameter. If you're worried about all the disk access from a template file just use mod_perl and the cache option detailed below.

The three new() calling methods can also be accessed as below, if you prefer.

  my $t = HTML::Template->new_file('file.tmpl', option => 'value');

  my $t = HTML::Template->new_scalar_ref($ref_to_template_text, 
                                        option => 'value');

  my $t = HTML::Template->new_array_ref($ref_to_array_of_lines, 
                                       option => 'value');

And as a final option, for those that might prefer it, you can call new as:

  my $t = HTML::Template->new(type => 'filename', 
                              source => 'file.tmpl');

Which works for all three of the source types.

If the environment variable HTML_TEMPLATE_ROOT is set and your filename doesn't begin with /, then the path will be relative to the value of $HTML_TEMPLATE_ROOT. Example - if the environment variable HTML_TEMPLATE_ROOT is set to "/home/sam" and I call HTML::Template->new() with filename set to "sam.tmpl", the HTML::Template will try to open "/home/sam/sam.tmpl" to access the template file. You can also affect the search path for files with the "path" option to new() - see below for more information.

You can modify the Template object's behavior with new. These options are available:

  • die_on_bad_params - if set to 0 the module will let you call $template->param(param_name => 'value') even if 'param_name' doesn't exist in the template body. Defaults to 1.

  • strict - if set to 0 the module will allow things that look like they might be TMPL_* tags to get by without dieing. Example:


    Would normally cause an error, but if you call new with strict => 0, HTML::Template will ignore it. Defaults to 1.

  • cache - if set to 1 the module will cache in memory the parsed templates based on the filename parameter and modification date of the file. This only applies to templates opened with the filename parameter specified, not scalarref or arrayref templates. Caching also looks at the modification times of any files included using <TMPL_INCLUDE> tags, but again, only if the template is opened with filename parameter. Note that different new() parameter settings do not cause a cache refresh, only a change in the modification time of the template will trigger a cache refresh. For most usages this is fine. My simplistic testing shows that using cache yields a 90% performance increase under mod_perl, more if you use large <TMPL_LOOP>s. Cache defaults to 0.

  • blind_cache - if set to 1 the module behaves exactly as with normal caching but does not check to see if the file has changed on each request. This option should be used with caution, but could be of use on high-load servers. My tests show blind_cache performing only 1 to 2 percent faster than cache under mod_perl.

  • associate - this option allows you to inherit the parameter values from other objects. The only requirement for the other object is that it have a param() method that works like HTML::Template's param(). A good candidate would be a CGI.pm query object. Example:

      my $query = new CGI;
      my $template = HTML::Template->new(filename => 'template.tmpl',
                                         associate => $query);

    Now, $template->output() will act as though

      $template->param('FormField', $cgi->param('FormField'));

    had been specified for each key/value pair that would be provided by the $cgi->param() method. Parameters you set directly take precedence over associated parameters.

    You can specify multiple objects to associate by passing an anonymous array to the associate option. They are searched for parameters in the order they appear:

      my $template = HTML::Template->new(filename => 'template.tmpl',
                                         associate => [$query, $other_obj]);

    The old associateCGI() call is still supported, but should be considered obsolete.

  • loop_context_vars - when this parameter is set to true (it is false by default) three loop context varaiables are made available inside a loop: __FIRST__, __LAST__ and __INNER__. They can be used with <TMPL_IF> and <TMPL_ELSE> to control how a loop is output. Example:

          <TMPL_IF NAME="__FIRST__">
            This only outputs on the first pass.
          <TMPL_IF NAME="__INNER__">
            This outputs on passes that are neither first nor last.
          <TMPL_IF NAME="__LAST__">
            This only outputs on the last pass.

    One use of this feature is to provide a "separator" similar in effect to the perl function join(). Example:

          <TMPL_IF __LAST__> and </TMPL_IF>

    Would output (in a browser) something like:

      Apples, Oranges, Brains, Toes, and Kiwi.

    Given an appropriate param() call, of course. NOTE: A loop with only a single pass will get both __FIRST__ and __LAST__ set to true, but not __INNER__.

  • path - you can set this variable with a list of paths to search for files specified with the "filename" option to new() and for files included with the <TMPL_INCLUDE> tag. This list is only consulted when the filename is relative - i.e. does not begin with a '/'. The HTML_TEMPLATE_ROOT environment variable is always tried first if it exists. In the case of a <TMPL_INCLUDE> file, the path to the including file is also tried before path is consulted.


       my $template = HTML::Template->new( filename => 'file.tmpl',
                                           path => [ '/path/to/templates',
    =item *

    max_includes - set this variable to determine the maximum depth that includes can reach. Set to 10 by default. Including files to a depth greater than this value causes an error message to be displayed. Set to 0 to disable this protection.

  • vanguard_compatibility_mode - if set to 1 the module will expect to see <TMPL_VAR>s that look like %NAME% instead of the standard syntax. Also sets die_on_bad_params => 0. If you're not at Vanguard Media trying to use an old format template don't worry about this one. Defaults to 0.

  • debug - if set to 1 the module will write random debugging information to STDERR. Defaults to 0.

  • debug_stack - if set to 1 the module will use Data::Dumper to print out the contents of the parse_stack to STDERR. Defaults to 0.

  • cache_debug - if set to 1 the module will send information on cache loads, hits and misses to STDERR. Defaults to 0.


param() can be called in a number of ways

1) To return a list of parameters in the template :

   my @parameter_names = $self->param();

2) To return the value set to a param :

   my $value = $self->param('PARAM');


3) To set the value of a parameter :

      # For simple TMPL_VARs:
      $self->param(PARAM => 'value');

      # And TMPL_LOOPs:
      $self->param(LOOP_PARAM => 
                    { PARAM => VALUE_FOR_FIRST_PASS, ... }, 
                    { PARAM => VALUE_FOR_SECOND_PASS, ... } 

4) To set the value of a a number of parameters :

     # For simple TMPL_VARs:
     $self->param(PARAM => 'value', 
                  PARAM2 => 'value'

      # And with some TMPL_LOOPs:
      $self->param(PARAM => 'value', 
                   PARAM2 => 'value',
                   LOOP_PARAM => 
                    { PARAM => VALUE_FOR_FIRST_PASS, ... }, 
                    { PARAM => VALUE_FOR_SECOND_PASS, ... } 
                   ANOTHER_LOOP_PARAM => 
                    { PARAM => VALUE_FOR_FIRST_PASS, ... }, 
                    { PARAM => VALUE_FOR_SECOND_PASS, ... } 

5) To set the value of a a number of parameters using a hash-ref :

                      PARAM => 'value', 
                      PARAM2 => 'value',
                      LOOP_PARAM => 
                        { PARAM => VALUE_FOR_FIRST_PASS, ... }, 
                        { PARAM => VALUE_FOR_SECOND_PASS, ... } 
                      ANOTHER_LOOP_PARAM => 
                        { PARAM => VALUE_FOR_FIRST_PASS, ... }, 
                        { PARAM => VALUE_FOR_SECOND_PASS, ... } 


Sets all the parameters to undef. Useful internally, if nowhere else!


output() returns the final result of the template. In most situations you'll want to print this, like:

   print $template->output();

When output is called each occurrence of <TMPL_VAR NAME=name> is replaced with the value assigned to "name" via param(). If a named parameter is unset it is simply replaced with ''. <TMPL_LOOPS> are evaluated once per parameter set, accumlating output on each pass.

Calling output() is guaranteed not to change the state of the Template object, in case you were wondering. This property is mostly important for the internal implementation of loops.


In the interest of greater understanding I've started a FAQ section of the perldocs. Please look in here before you send me email.

Is there a place to go to discuss HTML::Template and/or get help?

There's a mailing-list for HTML::Template at htmltmpl@lists.vm.com. Send a blank message to htmltmpl-subscribe@lists.vm.com to join!

I want support for <TMPL_XXX>! How about it?

Maybe. I definitely encourage people to discuss their ideas for HTML::Template on the mailing list. Please be ready to explain to me how the new tag fits in with HTML::Template's mission to provide a fast, lightweight system for using HTML templates.

NOTE: Offering to program said addition and provide it in the form of a patch to the most recent version of HTML::Template will definitely have a softening effect on potential opponents!

I found a bug, can you fix it?

That depends. Did you send me the VERSION of HTML::Template, a test script and a test template? If so, then almost certainly.

<TMPL_VAR>s from the main template aren't working inside a <TMPL_LOOP>! Why?

This is the intended behavior. <TMPL_LOOP> introduces a separate scope for <TMPL_VAR>s much like a subroutine call in Perl introduces a separate scope for "my" variables. If you need to have a variable from the main template work inside a loop you'll need to manually provide the value for each iteration of the loop.

Why do you use /[Tt]/ instead of /t/i? It's so ugly!

Simple - the case-insensitive match switch is very inefficient. According to _Mastering_Regular_Expressions_ from O'Reilly Press, /[Tt]/ is faster and more space efficient than /t/i - by as much as double against long strings. //i essentially does a lc() on the string and keeps a temporary copy in memory.

When this changes, and it is in the 5.6 development series, I will gladly use //i. Believe me, I realize [Tt] is hideously ugly.

How can I pre-load my templates using cache-mode and mod_perl?

Add something like this to your startup.pl:

   use HTML::Template;
   use File::Find;

   print STDERR "Pre-loading HTML Templates...\n";
        sub {
          return unless /\.tmpl$/;
                              filename => "$File::Find::dir/$_",
                              cache => 1,

Note that you'll need to modify the "return unless" line to specify the extension you use for your template files - I use .tmpl, as you can see. You'll also need to specify the path to your template files.

One potential problem: the "/path/to/templates/" must be EXACTLY the same path you use when you call HTML::Template->new(). Otherwise the cache won't know they're the same file and will load a new copy - instead getting a speed increase, you'll double your memory usage. To find out if this is happening set cache_debug => 1 in your application code and look for "CACHE MISS" messages in the logs.

What characters are allowed in TMPL_* NAMEs?

Numbers, letters, '.', '/', '+', '-' and '_'.


I am aware of no bugs - if you find one, join the mailing list and tell us about it (htmltmpl@lists.vm.com). You can join the HTML::Template mailing-list by sending a blank email to htmltmpl-subscribe@lists.vm.com. Of course, you can still email me directly (sam@tregar.com) with bugs, but I reserve the right to forward said bug reports to the mailing list.

When submitting bug reports, be sure to include full details, including the VERSION of the module, a test script and a test template demonstrating the problem!


This module was the brain child of my boss, Jesse Erlbaum (jesse@vm.com) here at Vanguard Media. The most original idea in this module - the <TMPL_LOOP> - was entirely his.

Fixes, Bug Reports, Optimizations and Ideas have been generously provided by:

   Richard Chen
   Mike Blazer
   Adriano Nagelschmidt Rodrigues
   Andrej Mikus
   Ilya Obshadko
   Kevin Puetz
   Steve Reppucci
   Richard Dice
   Tom Hukins
   Eric Zylberstejn
   David Glasser
   Peter Marelas
   James William Carlson
   Frank D. Cringle
   Winfried Koenig
   Matthew Wickline



Sam Tregar, sam@tregar.com (you can also find me on the mailing list at htmltmpl@lists.vm.com - join it by sending a blank message to htmltmpl-subscribe@lists.vm.com).


HTML::Template : A module for using HTML Templates with Perl

Copyright (C) 1999 Sam Tregar (sam@tregar.com)

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

1 POD Error

The following errors were encountered while parsing the POD:

Around line 558:

=back doesn't take any parameters, but you said =back 4