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


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:

  #!/usr/bin/perl -w
  use HTML::Template;
  # open the html template
  my $template = HTML::Template->new(filename => 'test.tmpl');
  # fill in some parameters
  $template->param(HOME => $ENV{HOME});
  $template->param(PATH => $ENV{PATH});
  # send the obligatory Content-Type and print the template output
  print "Content-Type: text/html\n\n", $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>, <TMPL_ELSE> and <TMPL_UNLESS>. 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.


If you're new to HTML::Template, I suggest you start with the introductory article available on the HTML::Template website:


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 <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=HTML'' option in the tag to indicate that you want the value to be HTML-escaped before being returned from output (the old ESCAPE=1 syntax is still supported). 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:

   <input name=param type=text value="<TMPL_VAR NAME="PARAM">">

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=HTML, like this:

   <input name=param type=text value="<TMPL_VAR ESCAPE=HTML NAME="PARAM">">

You'll get what you wanted no matter what value happens to be passed in for param. You can also write ESCAPE=``HTML'', ESCAPE='HTML' and ESCAPE='1'.

``ESCAPE=0'' and ``ESCAPE=NONE'' turn off escaping, which is the default behavior.

There is also the ``ESCAPE=URL'' option which may be used for VARs that populate a URL. It will do URL escaping, like replacing ' ' with '+' and '/' with '%2F'.

There is also the ``ESCAPE=JS'' option which may be used for VARs that need to be placed within a Javascript string. All \n, \r, ' and `` characters are escaped.

You can assign a default value to a variable with the DEFAULT attribute. For example, this will output ``the devil gave me a taco'' if the ``who'' variable is not set.

  The <TMPL_VAR NAME=WHO DEFAULT=devil> gave me a taco.



The <TMPL_LOOP> tag is a bit more complicated than <TMPL_VAR>. The <TMPL_LOOP> tag allows you to delimit a section of text and give it a name. Inside this named loop you place <TMPL_VAR>s. Now you pass to param() a list (an array ref) of parameter assignments (hash refs) for this loop. The loop iterates over the 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> <br>
      Job:  <TMPL_VAR NAME=JOB>  <p>
 In the script:
   $template->param(EMPLOYEE_INFO => [ 
                                       { name => 'Sam', job => 'programmer' },
                                       { name => 'Steve', job => 'soda jerk' },
   print $template->output();
 The output in a browser:
   Name: Sam
   Job: programmer
   Name: Steve
   Job: soda jerk

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
   while (@words and @numbers) {
     my %row_data;  # get a fresh hash for the row data
     # fill in this row
     $row_data{WORD} = shift @words;
     $row_data{NUMBER} = shift @numbers;
     # 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:

  $template->param(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.

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 perl subroutine call. If you want your variables to be global you can use 'global_vars' option to new() described below.


  <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 are used exactly as if its contents were physically included in the master template.

The file specified can be an absolute path (beginning with a '/' under Unix, for example). If it isn't absolute, the path to the enclosing file is tried first. After that the path in the environment variable HTML_TEMPLATE_ROOT is tried, if it exists. Next, the ``path'' option is consulted, first as-is and then with HTML_TEMPLATE_ROOT prepended if available. 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.

   Not going to work:

If the name of a TMPL_LOOP is used in a TMPL_IF, the IF block will output if the loop has at least one row. Example:

    This will output if the loop is not empty.

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.

If the name of a TMPL_LOOP is used in a TMPL_UNLESS, the UNLESS block output if the loop has zero rows.

    This will output if the loop is empty.


HTML::Template's tags are meant to mimic normal HTML tags. However, they are allowed to ``break the rules''. Something like:

   <img src="<TMPL_VAR IMAGE_SRC>">

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 this documentation.



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. In almost every case you'll want to use the filename parameter. If you're worried about all the disk access from reading a template file just use mod_perl and the cache option detailed below.

You can also read the template from an already opened filehandle, either traditionally as a glob or as a FileHandle:

  my $t = HTML::Template->new( filehandle => *FH, option => 'value');

The four 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');
  my $t = HTML::Template->new_filehandle($fh, 
                                       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(). The options are available:

Error Detection Options
Caching Options
Filesystem Options
Debugging Options
Miscellaneous Options


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');
      # with a subroutine reference that gets called to get the value
      # of the scalar.  The sub will recieve the template object as a
      # parameter.
      $self->param(PARAM => sub { return '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, ... } 

An error occurs if you try to set a value that is tainted if the ``force_untaint'' option is set.


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.

You may optionally supply a filehandle to print to automatically as the template is generated. This may improve performance and lower memory consumption. Example:

   $template->output(print_to => *STDOUT);

The return value is undefined when using the print_to option.


This method allow you to get information about the template structure. It can be called in a number of ways. The simplest usage of query is simply to check whether a parameter name exists in the template, using the name option:

  if ($template->query(name => 'foo')) {
    # do something if a varaible of any type 
    # named FOO is in the template

This same usage returns the type of the parameter. The type is the same as the tag minus the leading 'TMPL_'. So, for example, a TMPL_VAR parameter returns 'VAR' from query().

  if ($template->query(name => 'foo') eq 'VAR') {
    # do something if FOO exists and is a TMPL_VAR

Note that the variables associated with TMPL_IFs and TMPL_UNLESSs will be identified as 'VAR' unless they are also used in a TMPL_LOOP, in which case they will return 'LOOP'.

query() also allows you to get a list of parameters inside a loop (and inside loops inside loops). Example loop:


And some query calls:

  # returns 'LOOP'
  $type = $template->query(name => 'EXAMPLE_LOOP');

  # returns ('bop', 'bee', 'example_inner_loop')
  @param_names = $template->query(loop => 'EXAMPLE_LOOP');
  # both return 'VAR'
  $type = $template->query(name => ['EXAMPLE_LOOP', 'BEE']);
  $type = $template->query(name => ['EXAMPLE_LOOP', 'BOP']);
  # and this one returns 'LOOP'
  $type = $template->query(name => ['EXAMPLE_LOOP', 
  # and finally, this returns ('inner_bee', 'inner_bop')
  @inner_param_names = $template->query(loop => ['EXAMPLE_LOOP',
  # for non existent parameter names you get undef
  # this returns undef.
  $type = $template->query(name => 'DWEAZLE_ZAPPA');
  # calling loop on a non-loop parameter name will cause an error.
  # this dies:
  $type = $template->query(loop => 'DWEAZLE_ZAPPA');

As you can see above the loop option returns a list of parameter names and both name and loop take array refs in order to refer to parameters inside loops. It is an error to use loop with a parameter that is not a loop.

Note that all the names are returned in lowercase and the types are uppercase.

Just like param(), query() with no arguments returns all the parameter names in the template at the top level.


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

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

    A: There's a mailing-list for discussing HTML::Template at To join:

    If you just want to get email when new releases are available you can join the announcements mailing-list here:
    =item 2

    Q: Is there a searchable archive for the mailing-list?

    A: Yes, you can find an archive of the SourceForge list here:

    For an archive of the old list, setup by Sean P. Scanlon, see:

  2. Q: I want support for <TMPL_XXX>! How about it?

    A: 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!

  3. Q: I found a bug, can you fix it?

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

    If you're feeling really adventurous, HTML::Template has a publically available Subversion server. See below for more information in the PUBLIC SUBVERSION SERVER section.

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

    A: 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 want your <TMPL_VAR>s to be global you can set the 'global_vars' option when you call new(). See above for documentation of the 'global_vars' new() option.

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

    A: 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.

  6. Q: How can I pre-load my templates using cache-mode and mod_perl?

    A: Add something like this to your

       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.

  7. Q: What characters are allowed in TMPL_* NAMEs?

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

  8. Q: How can I execute a program from inside my template?

    A: Short answer: you can't. Longer answer: you shouldn't since this violates the fundamental concept behind HTML::Template - that design and code should be seperate.

    But, inevitably some people still want to do it. If that describes you then you should take a look at HTML::Template::Expr. Using HTML::Template::Expr it should be easy to write a run_program() function. Then you can do awful stuff like:

      <tmpl_var expr="run_program('')">

    Just, please, don't tell me about it. I'm feeling guilty enough just for writing HTML::Template::Expr in the first place.

  9. Q: Can I get a copy of these docs in Japanese?

    A: Yes you can. See Kawai Takanori's translation at:

  10. Q: What's the best way to create a <select> form element using HTML::Template?

    A: There is much disagreement on this issue. My personal preference is to use's excellent popup_menu() and scrolling_list() functions to fill in a single <tmpl_var select_foo> variable.

    To some people this smacks of mixing HTML and code in a way that they hoped HTML::Template would help them avoid. To them I'd say that HTML is a violation of the principle of separating design from programming. There's no clear separation between the programmatic elements of the <form> tags and the layout of the <form> tags. You'll have to draw the line somewhere - clearly the designer can't be entirely in charge of form creation.

    It's a balancing act and you have to weigh the pros and cons on each side. It is certainly possible to produce a <select> element entirely inside the template. What you end up with is a rat's nest of loops and conditionals. Alternately you can give up a certain amount of flexibility in return for vastly simplifying your templates. I generally choose the latter.

    Another option is to investigate HTML::FillInForm which some have reported success using to solve this problem.


I am aware of no bugs - if you find one, join the mailing list and tell us about it. You can join the HTML::Template mailing-list by visiting:

Of course, you can still email me directly ( with bugs, but I reserve the right to forward 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!

If you're feeling really adventurous, HTML::Template has a publically available Subversion server. See below for more information in the PUBLIC SUBVERSION SERVER section.


This module was the brain child of my boss, Jesse Erlbaum ( ) 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
   Doug Steinwand
   Drew Taylor
   Tobias Brox
   Michael Lloyd
   Simran Gambhir
   Chris Houser <>
   Larry Moore
   Todd Larason
   Jody Biggs
   T.J. Mather
   Martin Schroth
   Dave Wolfe
   Kawai Takanori
   Peter Guelich
   Chris Nokleberg
   Ralph Corderoy
   William Ward
   Ade Olonoh
   Mark Stosberg
   Lance Thomas
   Roland Giersig
   Jere Julian
   Peter Leonard
   Kenny Smith
   Sean P. Scanlon
   Martin Pfeffer
   David Ferrance
   Gyepi Sam  
   Darren Chamberlain
   Paul Baker
   Gabor Szabo
   Craig Manley
   Richard Fein
   The Phalanx Project
   Sven Neuhaus



You can find information about HTML::Template and other related modules at:


HTML::Template now has a publicly accessible Subversion server provided by SourceForge ( You can access it by going to Give it a try!


Sam Tregar,


  HTML::Template : A module for using HTML Templates with Perl
  Copyright (C) 2000-2002 Sam Tregar (

  This module is free software; you can redistribute it and/or modify it
  under the terms of either:

  a) the GNU General Public License as published by the Free Software
  Foundation; either version 1, or (at your option) any later version,

  b) the "Artistic License" which comes with this module.

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

  You should have received a copy of the Artistic License with this
  module, in the file ARTISTIC.  If not, I'll be glad to provide one.

  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

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