1Template(3)           User Contributed Perl Documentation          Template(3)
2
3
4

NAME

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

SYNOPSIS

9       First you make a template - this is just a normal HTML file with a few
10       extra tags, the simplest being <TMPL_VAR>
11
12       For example, test.tmpl:
13
14         <html>
15         <head><title>Test Template</title>
16         <body>
17         My Home Directory is <TMPL_VAR NAME=HOME>
18         <p>
19         My Path is set to <TMPL_VAR NAME=PATH>
20         </body>
21         </html>
22
23       Now create a small CGI program:
24
25         #!/usr/bin/perl -w
26         use HTML::Template;
27
28         # open the html template
29         my $template = HTML::Template->new(filename => 'test.tmpl');
30
31         # fill in some parameters
32         $template->param(HOME => $ENV{HOME});
33         $template->param(PATH => $ENV{PATH});
34
35         # send the obligatory Content-Type and print the template output
36         print "Content-Type: text/html\n\n", $template->output;
37
38       If all is well in the universe this should show something like this in
39       your browser when visiting the CGI:
40
41         My Home Directory is /home/some/directory
42         My Path is set to /bin;/usr/bin
43

DESCRIPTION

45       This module attempts to make using HTML templates simple and natural.
46       It extends standard HTML with a few new HTML-esque tags - <TMPL_VAR>,
47       <TMPL_LOOP>, <TMPL_INCLUDE>, <TMPL_IF>, <TMPL_ELSE> and <TMPL_UNLESS>.
48       The file written with HTML and these new tags is called a template.  It
49       is usually saved separate from your script - possibly even created by
50       someone else!  Using this module you fill in the values for the vari‐
51       ables, loops and branches declared in the template.  This allows you to
52       separate design - the HTML - from the data, which you generate in the
53       Perl script.
54
55       This module is licensed under the GPL.  See the LICENSE section below
56       for more details.
57

TUTORIAL

59       If you're new to HTML::Template, I suggest you start with the introduc‐
60       tory article available on the HTML::Template website:
61
62          http://html-template.sourceforge.net
63

MOTIVATION

65       It is true that there are a number of packages out there to do HTML
66       templates.  On the one hand you have things like HTML::Embperl which
67       allows you freely mix Perl with HTML.  On the other hand lie home-grown
68       variable substitution solutions.  Hopefully the module can find a place
69       between the two.
70
71       One advantage of this module over a full HTML::Embperl-esque solution
72       is that it enforces an important divide - design and programming.  By
73       limiting the programmer to just using simple variables and loops in the
74       HTML, the template remains accessible to designers and other non-perl
75       people.  The use of HTML-esque syntax goes further to make the format
76       understandable to others.  In the future this similarity could be used
77       to extend existing HTML editors/analyzers to support HTML::Template.
78
79       An advantage of this module over home-grown tag-replacement schemes is
80       the support for loops.  In my work I am often called on to produce
81       tables of data in html.  Producing them using simplistic HTML templates
82       results in CGIs containing lots of HTML since the HTML itself cannot
83       represent loops.  The introduction of loop statements in the HTML sim‐
84       plifies this situation considerably.  The designer can layout a single
85       row and the programmer can fill it in as many times as necessary - all
86       they must agree on is the parameter names.
87
88       For all that, I think the best thing about this module is that it does
89       just one thing and it does it quickly and carefully.  It doesn't try to
90       replace Perl and HTML, it just augments them to interact a little bet‐
91       ter.  And it's pretty fast.
92

THE TAGS

94       TMPL_VAR
95
96         <TMPL_VAR NAME="PARAMETER_NAME">
97
98       The <TMPL_VAR> tag is very simple.  For each <TMPL_VAR> tag in the tem‐
99       plate you call $template->param(PARAMETER_NAME => "VALUE").  When the
100       template is output the <TMPL_VAR> is replaced with the VALUE text you
101       specified.  If you don't set a parameter it just gets skipped in the
102       output.
103
104       Optionally you can use the "ESCAPE=HTML" option in the tag to indicate
105       that you want the value to be HTML-escaped before being returned from
106       output (the old ESCAPE=1 syntax is still supported).  This means that
107       the ", <, >, and & characters get translated into &quot;, &lt;, &gt;
108       and &amp; respectively.  This is useful when you want to use a TMPL_VAR
109       in a context where those characters would cause trouble.  Example:
110
111          <input name=param type=text value="<TMPL_VAR NAME="PARAM">">
112
113       If you called "param()" with a value like sam"my you'll get in trouble
114       with HTML's idea of a double-quote.  On the other hand, if you use
115       ESCAPE=HTML, like this:
116
117          <input name=param type=text value="<TMPL_VAR ESCAPE=HTML NAME="PARAM">">
118
119       You'll get what you wanted no matter what value happens to be passed in
120       for param.  You can also write ESCAPE="HTML", ESCAPE='HTML' and
121       ESCAPE='1'.
122
123       "ESCAPE=0" and "ESCAPE=NONE" turn off escaping, which is the default
124       behavior.
125
126       There is also the "ESCAPE=URL" option which may be used for VARs that
127       populate a URL.  It will do URL escaping, like replacing ' ' with '+'
128       and '/' with '%2F'.
129
130       There is also the "ESCAPE=JS" option which may be used for VARs that
131       need to be placed within a Javascript string. All \n, \r, ' and " char‐
132       acters are escaped.
133
134       You can assign a default value to a variable with the DEFAULT
135       attribute.  For example, this will output "the devil gave me a taco" if
136       the "who" variable is not set.
137
138         The <TMPL_VAR NAME=WHO DEFAULT=devil> gave me a taco.
139
140       TMPL_LOOP
141
142         <TMPL_LOOP NAME="LOOP_NAME"> ... </TMPL_LOOP>
143
144       The <TMPL_LOOP> tag is a bit more complicated than <TMPL_VAR>.  The
145       <TMPL_LOOP> tag allows you to delimit a section of text and give it a
146       name.  Inside this named loop you place <TMPL_VAR>s.  Now you pass to
147       "param()" a list (an array ref) of parameter assignments (hash refs)
148       for this loop.  The loop iterates over the list and produces output
149       from the text block for each pass.  Unset parameters are skipped.
150       Here's an example:
151
152        In the template:
153
154          <TMPL_LOOP NAME=EMPLOYEE_INFO>
155             Name: <TMPL_VAR NAME=NAME> <br>
156             Job:  <TMPL_VAR NAME=JOB>  <p>
157          </TMPL_LOOP>
158
159        In the script:
160
161          $template->param(EMPLOYEE_INFO => [
162                                              { name => 'Sam', job => 'programmer' },
163                                              { name => 'Steve', job => 'soda jerk' },
164                                            ]
165                          );
166          print $template->output();
167
168        The output in a browser:
169
170          Name: Sam
171          Job: programmer
172
173          Name: Steve
174          Job: soda jerk
175
176       As you can see above the <TMPL_LOOP> takes a list of variable assign‐
177       ments and then iterates over the loop body producing output.
178
179       Often you'll want to generate a <TMPL_LOOP>'s contents programmati‐
180       cally.  Here's an example of how this can be done (many other ways are
181       possible!):
182
183          # a couple of arrays of data to put in a loop:
184          my @words = qw(I Am Cool);
185          my @numbers = qw(1 2 3);
186
187          my @loop_data = ();  # initialize an array to hold your loop
188
189          while (@words and @numbers) {
190            my %row_data;  # get a fresh hash for the row data
191
192            # fill in this row
193            $row_data{WORD} = shift @words;
194            $row_data{NUMBER} = shift @numbers;
195
196            # the crucial step - push a reference to this row into the loop!
197            push(@loop_data, \%row_data);
198          }
199
200          # finally, assign the loop data to the loop param, again with a
201          # reference:
202          $template->param(THIS_LOOP => \@loop_data);
203
204       The above example would work with a template like:
205
206          <TMPL_LOOP NAME="THIS_LOOP">
207             Word: <TMPL_VAR NAME="WORD">     <br>
208             Number: <TMPL_VAR NAME="NUMBER"> <p>
209          </TMPL_LOOP>
210
211       It would produce output like:
212
213          Word: I
214          Number: 1
215
216          Word: Am
217          Number: 2
218
219          Word: Cool
220          Number: 3
221
222       <TMPL_LOOP>s within <TMPL_LOOP>s are fine and work as you would expect.
223       If the syntax for the "param()" call has you stumped, here's an example
224       of a param call with one nested loop:
225
226         $template->param(LOOP => [
227                                   { name => 'Bobby',
228                                     nicknames => [
229                                                   { name => 'the big bad wolf' },
230                                                   { name => 'He-Man' },
231                                                  ],
232                                   },
233                                  ],
234                         );
235
236       Basically, each <TMPL_LOOP> gets an array reference.  Inside the array
237       are any number of hash references.  These hashes contain the
238       name=>value pairs for a single pass over the loop template.
239
240       Inside a <TMPL_LOOP>, the only variables that are usable are the ones
241       from the <TMPL_LOOP>.  The variables in the outer blocks are not visi‐
242       ble within a template loop.  For the computer-science geeks among you,
243       a <TMPL_LOOP> introduces a new scope much like a perl subroutine call.
244       If you want your variables to be global you can use 'global_vars'
245       option to new() described below.
246
247       TMPL_INCLUDE
248
249         <TMPL_INCLUDE NAME="filename.tmpl">
250
251       This tag includes a template directly into the current template at the
252       point where the tag is found.  The included template contents are used
253       exactly as if its contents were physically included in the master tem‐
254       plate.
255
256       The file specified can be an absolute path (beginning with a '/' under
257       Unix, for example).  If it isn't absolute, the path to the enclosing
258       file is tried first.  After that the path in the environment variable
259       HTML_TEMPLATE_ROOT is tried, if it exists.  Next, the "path" option is
260       consulted, first as-is and then with HTML_TEMPLATE_ROOT prepended if
261       available.  As a final attempt, the filename is passed to open()
262       directly.  See below for more information on HTML_TEMPLATE_ROOT and the
263       "path" option to new().
264
265       As a protection against infinitly recursive includes, an arbitary limit
266       of 10 levels deep is imposed.  You can alter this limit with the
267       "max_includes" option.  See the entry for the "max_includes" option
268       below for more details.
269
270       TMPL_IF
271
272         <TMPL_IF NAME="PARAMETER_NAME"> ... </TMPL_IF>
273
274       The <TMPL_IF> tag allows you to include or not include a block of the
275       template based on the value of a given parameter name.  If the parame‐
276       ter is given a value that is true for Perl - like '1' - then the block
277       is included in the output.  If it is not defined, or given a false
278       value - like '0' - then it is skipped.  The parameters are specified
279       the same way as with TMPL_VAR.
280
281       Example Template:
282
283          <TMPL_IF NAME="BOOL">
284            Some text that only gets displayed if BOOL is true!
285          </TMPL_IF>
286
287       Now if you call $template->param(BOOL => 1) then the above block will
288       be included by output.
289
290       <TMPL_IF> </TMPL_IF> blocks can include any valid HTML::Template con‐
291       struct - VARs and LOOPs and other IF/ELSE blocks.  Note, however, that
292       intersecting a <TMPL_IF> and a <TMPL_LOOP> is invalid.
293
294          Not going to work:
295          <TMPL_IF BOOL>
296             <TMPL_LOOP SOME_LOOP>
297          </TMPL_IF>
298             </TMPL_LOOP>
299
300       If the name of a TMPL_LOOP is used in a TMPL_IF, the IF block will out‐
301       put if the loop has at least one row.  Example:
302
303         <TMPL_IF LOOP_ONE>
304           This will output if the loop is not empty.
305         </TMPL_IF>
306
307         <TMPL_LOOP LOOP_ONE>
308           ....
309         </TMPL_LOOP>
310
311       WARNING: Much of the benefit of HTML::Template is in decoupling your
312       Perl and HTML.  If you introduce numerous cases where you have TMPL_IFs
313       and matching Perl if()s, you will create a maintenance problem in keep‐
314       ing the two synchronized.  I suggest you adopt the practice of only
315       using TMPL_IF if you can do so without requiring a matching if() in
316       your Perl code.
317
318       TMPL_ELSE
319
320         <TMPL_IF NAME="PARAMETER_NAME"> ... <TMPL_ELSE> ... </TMPL_IF>
321
322       You can include an alternate block in your TMPL_IF block by using
323       TMPL_ELSE.  NOTE: You still end the block with </TMPL_IF>, not
324       </TMPL_ELSE>!
325
326          Example:
327
328          <TMPL_IF BOOL>
329            Some text that is included only if BOOL is true
330          <TMPL_ELSE>
331            Some text that is included only if BOOL is false
332          </TMPL_IF>
333
334       TMPL_UNLESS
335
336         <TMPL_UNLESS NAME="PARAMETER_NAME"> ... </TMPL_UNLESS>
337
338       This tag is the opposite of <TMPL_IF>.  The block is output if the CON‐
339       TROL_PARAMETER is set false or not defined.  You can use <TMPL_ELSE>
340       with <TMPL_UNLESS> just as you can with <TMPL_IF>.
341
342         Example:
343
344         <TMPL_UNLESS BOOL>
345           Some text that is output only if BOOL is FALSE.
346         <TMPL_ELSE>
347           Some text that is output only if BOOL is TRUE.
348         </TMPL_UNLESS>
349
350       If the name of a TMPL_LOOP is used in a TMPL_UNLESS, the UNLESS block
351       output if the loop has zero rows.
352
353         <TMPL_UNLESS LOOP_ONE>
354           This will output if the loop is empty.
355         </TMPL_UNLESS>
356
357         <TMPL_LOOP LOOP_ONE>
358           ....
359         </TMPL_LOOP>
360
361       NOTES
362
363       HTML::Template's tags are meant to mimic normal HTML tags.  However,
364       they are allowed to "break the rules".  Something like:
365
366          <img src="<TMPL_VAR IMAGE_SRC>">
367
368       is not really valid HTML, but it is a perfectly valid use and will work
369       as planned.
370
371       The "NAME=" in the tag is optional, although for extensibility's sake I
372       recommend using it.  Example - "<TMPL_LOOP LOOP_NAME>" is acceptable.
373
374       If you're a fanatic about valid HTML and would like your templates to
375       conform to valid HTML syntax, you may optionally type template tags in
376       the form of HTML comments. This may be of use to HTML authors who would
377       like to validate their templates' HTML syntax prior to HTML::Template
378       processing, or who use DTD-savvy editing tools.
379
380         <!-- TMPL_VAR NAME=PARAM1 -->
381
382       In order to realize a dramatic savings in bandwidth, the standard
383       (non-comment) tags will be used throughout this documentation.
384

METHODS

386       new()
387
388       Call new() to create a new Template object:
389
390         my $template = HTML::Template->new( filename => 'file.tmpl',
391                                             option => 'value'
392                                           );
393
394       You must call new() with at least one name => value pair specifying how
395       to access the template text.  You can use "filename => 'file.tmpl'" to
396       specify a filename to be opened as the template.  Alternately you can
397       use:
398
399         my $t = HTML::Template->new( scalarref => $ref_to_template_text,
400                                      option => 'value'
401                                    );
402
403       and
404
405         my $t = HTML::Template->new( arrayref => $ref_to_array_of_lines ,
406                                      option => 'value'
407                                    );
408
409       These initialize the template from in-memory resources.  In almost
410       every case you'll want to use the filename parameter.  If you're wor‐
411       ried about all the disk access from reading a template file just use
412       mod_perl and the cache option detailed below.
413
414       You can also read the template from an already opened filehandle,
415       either traditionally as a glob or as a FileHandle:
416
417         my $t = HTML::Template->new( filehandle => *FH, option => 'value');
418
419       The four new() calling methods can also be accessed as below, if you
420       prefer.
421
422         my $t = HTML::Template->new_file('file.tmpl', option => 'value');
423
424         my $t = HTML::Template->new_scalar_ref($ref_to_template_text,
425                                               option => 'value');
426
427         my $t = HTML::Template->new_array_ref($ref_to_array_of_lines,
428                                              option => 'value');
429
430         my $t = HTML::Template->new_filehandle($fh,
431                                              option => 'value');
432
433       And as a final option, for those that might prefer it, you can call new
434       as:
435
436         my $t = HTML::Template->new(type => 'filename',
437                                     source => 'file.tmpl');
438
439       Which works for all three of the source types.
440
441       If the environment variable HTML_TEMPLATE_ROOT is set and your filename
442       doesn't begin with /, then the path will be relative to the value of
443       $HTML_TEMPLATE_ROOT.  Example - if the environment variable HTML_TEM‐
444       PLATE_ROOT is set to "/home/sam" and I call HTML::Template->new() with
445       filename set to "sam.tmpl", the HTML::Template will try to open
446       "/home/sam/sam.tmpl" to access the template file.  You can also affect
447       the search path for files with the "path" option to new() - see below
448       for more information.
449
450       You can modify the Template object's behavior with new().  The options
451       are available:
452
453       Error Detection Options
454           *   die_on_bad_params - if set to 0 the module will let you call
455               $template->param(param_name => 'value') even if 'param_name'
456               doesn't exist in the template body.  Defaults to 1.
457
458           *   force_untaint - if set to 1 the module will not allow you to
459               set unescaped parameters with tainted values. If set to 2 you
460               will have to untaint all parameters, including ones with the
461               escape attribute.  This option makes sure you untaint every‐
462               thing so you don't accidentally introduce e.g. cross-site-
463               scripting (CSS) vulnerabilities. Requires taint mode. Defaults
464               to 0.
465
466           *   strict - if set to 0 the module will allow things that look
467               like they might be TMPL_* tags to get by without dieing.  Exam‐
468               ple:
469
470                  <TMPL_HUH NAME=ZUH>
471
472               Would normally cause an error, but if you call new with strict
473               => 0, HTML::Template will ignore it.  Defaults to 1.
474
475           *   vanguard_compatibility_mode - if set to 1 the module will
476               expect to see <TMPL_VAR>s that look like %NAME% in addition to
477               the standard syntax.  Also sets die_on_bad_params => 0.  If
478               you're not at Vanguard Media trying to use an old format tem‐
479               plate don't worry about this one.  Defaults to 0.
480
481       Caching Options
482           *   cache - if set to 1 the module will cache in memory the parsed
483               templates based on the filename parameter and modification date
484               of the file.  This only applies to templates opened with the
485               filename parameter specified, not scalarref or arrayref tem‐
486               plates.  Caching also looks at the modification times of any
487               files included using <TMPL_INCLUDE> tags, but again, only if
488               the template is opened with filename parameter.
489
490               This is mainly of use in a persistent environment like
491               Apache/mod_perl.  It has absolutely no benefit in a normal CGI
492               environment since the script is unloaded from memory after
493               every request.  For a cache that does work for normal CGIs see
494               the 'shared_cache' option below.
495
496               Note that different new() parameter settings do not cause a
497               cache refresh, only a change in the modification time of the
498               template will trigger a cache refresh.  For most usages this is
499               fine.  My simplistic testing shows that using cache yields a
500               90% performance increase under mod_perl.  Cache defaults to 0.
501
502           *   shared_cache - if set to 1 the module will store its cache in
503               shared memory using the IPC::SharedCache module (available from
504               CPAN).  The effect of this will be to maintain a single shared
505               copy of each parsed template for all instances of HTML::Tem‐
506               plate to use.  This can be a significant reduction in memory
507               usage in a multiple server environment.  As an example, on one
508               of our systems we use 4MB of template cache and maintain 25
509               httpd processes - shared_cache results in saving almost 100MB!
510               Of course, some reduction in speed versus normal caching is to
511               be expected.  Another difference between normal caching and
512               shared_cache is that shared_cache will work in a CGI environ‐
513               ment - normal caching is only useful in a persistent environ‐
514               ment like Apache/mod_perl.
515
516               By default HTML::Template uses the IPC key 'TMPL' as a shared
517               root segment (0x4c504d54 in hex), but this can be changed by
518               setting the 'ipc_key' new() parameter to another 4-character or
519               integer key.  Other options can be used to affect the shared
520               memory cache correspond to IPC::SharedCache options - ipc_mode,
521               ipc_segment_size and ipc_max_size.  See IPC::SharedCache for a
522               description of how these work - in most cases you shouldn't
523               need to change them from the defaults.
524
525               For more information about the shared memory cache system used
526               by HTML::Template see IPC::SharedCache.
527
528           *   double_cache - if set to 1 the module will use a combination of
529               shared_cache and normal cache mode for the best possible
530               caching.  Of course, it also uses the most memory of all the
531               cache modes.  All the same ipc_* options that work with
532               shared_cache apply to double_cache as well.  By default dou‐
533               ble_cache is off.
534
535           *   blind_cache - if set to 1 the module behaves exactly as with
536               normal caching but does not check to see if the file has
537               changed on each request.  This option should be used with cau‐
538               tion, but could be of use on high-load servers.  My tests show
539               blind_cache performing only 1 to 2 percent faster than cache
540               under mod_perl.
541
542               NOTE: Combining this option with shared_cache can result in
543               stale templates stuck permanently in shared memory!
544
545           *   file_cache - if set to 1 the module will store its cache in a
546               file using the Storable module.  It uses no additional memory,
547               and my simplistic testing shows that it yields a 50% perfor‐
548               mance advantage.  Like shared_cache, it will work in a CGI
549               environment. Default is 0.
550
551               If you set this option you must set the "file_cache_dir"
552               option.  See below for details.
553
554               NOTE: Storable using flock() to ensure safe access to cache
555               files.  Using file_cache on a system or filesystem (NFS) with‐
556               out flock() support is dangerous.
557
558           *   file_cache_dir - sets the directory where the module will store
559               the cache files if file_cache is enabled.  Your script will
560               need write permissions to this directory.  You'll also need to
561               make sure the sufficient space is available to store the cache
562               files.
563
564           *   file_cache_dir_mode - sets the file mode for newly created
565               file_cache directories and subdirectories.  Defaults to 0700
566               for security but this may be inconvenient if you do not have
567               access to the account running the webserver.
568
569           *   double_file_cache - if set to 1 the module will use a combina‐
570               tion of file_cache and normal cache mode for the best possible
571               caching.  The file_cache_* options that work with file_cache
572               apply to double_file_cache as well.  By default dou‐
573               ble_file_cache is 0.
574
575       Filesystem Options
576           *   path - you can set this variable with a list of paths to search
577               for files specified with the "filename" option to new() and for
578               files included with the <TMPL_INCLUDE> tag.  This list is only
579               consulted when the filename is relative.  The HTML_TEM‐
580               PLATE_ROOT environment variable is always tried first if it
581               exists.  Also, if HTML_TEMPLATE_ROOT is set then an attempt
582               will be made to prepend HTML_TEMPLATE_ROOT onto paths in the
583               path array.  In the case of a <TMPL_INCLUDE> file, the path to
584               the including file is also tried before path is consulted.
585
586               Example:
587
588                  my $template = HTML::Template->new( filename => 'file.tmpl',
589                                                      path => [ '/path/to/templates',
590                                                                '/alternate/path'
591                                                              ]
592                                                     );
593
594               NOTE: the paths in the path list must be expressed as UNIX
595               paths, separated by the forward-slash character ('/').
596
597           *   search_path_on_include - if set to a true value the module will
598               search from the top of the array of paths specified by the path
599               option on every <TMPL_INCLUDE> and use the first matching tem‐
600               plate found.  The normal behavior is to look only in the cur‐
601               rent directory for a template to include.  Defaults to 0.
602
603       Debugging Options
604           *   debug - if set to 1 the module will write random debugging
605               information to STDERR.  Defaults to 0.
606
607           *   stack_debug - if set to 1 the module will use Data::Dumper to
608               print out the contents of the parse_stack to STDERR.  Defaults
609               to 0.
610
611           *   cache_debug - if set to 1 the module will send information on
612               cache loads, hits and misses to STDERR.  Defaults to 0.
613
614           *   shared_cache_debug - if set to 1 the module will turn on the
615               debug option in IPC::SharedCache - see IPC::SharedCache for
616               details. Defaults to 0.
617
618           *   memory_debug - if set to 1 the module will send information on
619               cache memory usage to STDERR.  Requires the GTop module.
620               Defaults to 0.
621
622       Miscellaneous Options
623           *   associate - this option allows you to inherit the parameter
624               values from other objects.  The only requirement for the other
625               object is that it have a "param()" method that works like
626               HTML::Template's "param()".  A good candidate would be a CGI.pm
627               query object.  Example:
628
629                 my $query = new CGI;
630                 my $template = HTML::Template->new(filename => 'template.tmpl',
631                                                    associate => $query);
632
633               Now, "$template->output()" will act as though
634
635                 $template->param('FormField', $cgi->param('FormField'));
636
637               had been specified for each key/value pair that would be pro‐
638               vided by the "$cgi->param()" method.  Parameters you set
639               directly take precedence over associated parameters.
640
641               You can specify multiple objects to associate by passing an
642               anonymous array to the associate option.  They are searched for
643               parameters in the order they appear:
644
645                 my $template = HTML::Template->new(filename => 'template.tmpl',
646                                                    associate => [$query, $other_obj]);
647
648               The old associateCGI() call is still supported, but should be
649               considered obsolete.
650
651               NOTE: The parameter names are matched in a case-insensitve man‐
652               ner.  If you have two parameters in a CGI object like 'NAME'
653               and 'Name' one will be chosen randomly by associate.  This
654               behavior can be changed by the following option.
655
656           *   case_sensitive - setting this option to true causes HTML::Tem‐
657               plate to treat template variable names case-sensitively.  The
658               following example would only set one parameter without the
659               "case_sensitive" option:
660
661                 my $template = HTML::Template->new(filename => 'template.tmpl',
662                                                    case_sensitive => 1);
663                 $template->param(
664                   FieldA => 'foo',
665                   fIELDa => 'bar',
666                 );
667
668               This option defaults to off.
669
670               NOTE: with case_sensitive and loop_context_vars the special
671               loop variables are available in lower-case only.
672
673           *   loop_context_vars - when this parameter is set to true (it is
674               false by default) four loop context variables are made avail‐
675               able inside a loop: __first__, __last__, __inner__, __odd__.
676               They can be used with <TMPL_IF>, <TMPL_UNLESS> and <TMPL_ELSE>
677               to control how a loop is output.
678
679               In addition to the above, a __counter__ var is also made avail‐
680               able when loop context variables are turned on.
681
682               Example:
683
684                  <TMPL_LOOP NAME="FOO">
685                     <TMPL_IF NAME="__first__">
686                       This only outputs on the first pass.
687                     </TMPL_IF>
688
689                     <TMPL_IF NAME="__odd__">
690                       This outputs every other pass, on the odd passes.
691                     </TMPL_IF>
692
693                     <TMPL_UNLESS NAME="__odd__">
694                       This outputs every other pass, on the even passes.
695                     </TMPL_UNLESS>
696
697                     <TMPL_IF NAME="__inner__">
698                       This outputs on passes that are neither first nor last.
699                     </TMPL_IF>
700
701                     This is pass number <TMPL_VAR NAME="__counter__">.
702
703                     <TMPL_IF NAME="__last__">
704                       This only outputs on the last pass.
705                     </TMPL_IF>
706                  </TMPL_LOOP>
707
708               One use of this feature is to provide a "separator" similar in
709               effect to the perl function join().  Example:
710
711                  <TMPL_LOOP FRUIT>
712                     <TMPL_IF __last__> and </TMPL_IF>
713                     <TMPL_VAR KIND><TMPL_UNLESS __last__>, <TMPL_ELSE>.</TMPL_UNLESS>
714                  </TMPL_LOOP>
715
716               Would output (in a browser) something like:
717
718                 Apples, Oranges, Brains, Toes, and Kiwi.
719
720               Given an appropriate "param()" call, of course.  NOTE: A loop
721               with only a single pass will get both __first__ and __last__
722               set to true, but not __inner__.
723
724           *   no_includes - set this option to 1 to disallow the
725               <TMPL_INCLUDE> tag in the template file.  This can be used to
726               make opening untrusted templates slightly less dangerous.
727               Defaults to 0.
728
729           *   max_includes - set this variable to determine the maximum depth
730               that includes can reach.  Set to 10 by default.  Including
731               files to a depth greater than this value causes an error mes‐
732               sage to be displayed.  Set to 0 to disable this protection.
733
734           *   global_vars - normally variables declared outside a loop are
735               not available inside a loop.  This option makes <TMPL_VAR>s
736               like global variables in Perl - they have unlimited scope.
737               This option also affects <TMPL_IF> and <TMPL_UNLESS>.
738
739               Example:
740
741                 This is a normal variable: <TMPL_VAR NORMAL>.<P>
742
743                 <TMPL_LOOP NAME=FROOT_LOOP>
744                    Here it is inside the loop: <TMPL_VAR NORMAL><P>
745                 </TMPL_LOOP>
746
747               Normally this wouldn't work as expected, since <TMPL_VAR NOR‐
748               MAL>'s value outside the loop is not available inside the loop.
749
750               The global_vars option also allows you to access the values of
751               an enclosing loop within an inner loop.  For example, in this
752               loop the inner loop will have access to the value of OUTER_VAR
753               in the correct iteration:
754
755                  <TMPL_LOOP OUTER_LOOP>
756                     OUTER: <TMPL_VAR OUTER_VAR>
757                       <TMPL_LOOP INNER_LOOP>
758                          INNER: <TMPL_VAR INNER_VAR>
759                          INSIDE OUT: <TMPL_VAR OUTER_VAR>
760                       </TMPL_LOOP>
761                  </TMPL_LOOP>
762
763               One side-effect of global-vars is that variables you set with
764               param() that might otherwise be ignored when die_on_bad_params
765               is off will stick around.  This is necessary to allow inner
766               loops to access values set for outer loops that don't directly
767               use the value.
768
769               NOTE: "global_vars" is not "global_loops" (which does not
770               exist).  That means that loops you declare at one scope are not
771               available inside other loops even when "global_vars" is on.
772
773           *   filter - this option allows you to specify a filter for your
774               template files.  A filter is a subroutine that will be called
775               after HTML::Template reads your template file but before it
776               starts parsing template tags.
777
778               In the most simple usage, you simply assign a code reference to
779               the filter parameter.  This subroutine will recieve a single
780               argument - a reference to a string containing the template file
781               text.  Here is an example that accepts templates with tags that
782               look like "!!!ZAP_VAR FOO!!!" and transforms them into
783               HTML::Template tags:
784
785                  my $filter = sub {
786                    my $text_ref = shift;
787                    $$text_ref =~ s/!!!ZAP_(.*?)!!!/<TMPL_$1>/g;
788                  };
789
790                  # open zap.tmpl using the above filter
791                  my $template = HTML::Template->new(filename => 'zap.tmpl',
792                                                     filter => $filter);
793
794               More complicated usages are possible.  You can request that
795               your filter receieve the template text as an array of lines
796               rather than as a single scalar.  To do that you need to specify
797               your filter using a hash-ref.  In this form you specify the
798               filter using the "sub" key and the desired argument format
799               using the "format" key.  The available formats are "scalar" and
800               "array".  Using the "array" format will incur a performance
801               penalty but may be more convenient in some situations.
802
803                  my $template = HTML::Template->new(filename => 'zap.tmpl',
804                                                     filter => { sub => $filter,
805                                                                 format => 'array' });
806
807               You may also have multiple filters.  This allows simple filters
808               to be combined for more elaborate functionality.  To do this
809               you specify an array of filters.  The filters are applied in
810               the order they are specified.
811
812                  my $template = HTML::Template->new(filename => 'zap.tmpl',
813                                                     filter => [
814                                                          { sub => \&decompress,
815                                                            format => 'scalar' },
816                                                          { sub => \&remove_spaces,
817                                                            format => 'array' }
818                                                       ]);
819
820               The specified filters will be called for any TMPL_INCLUDEed
821               files just as they are for the main template file.
822
823           *   default_escape - Set this parameter to "HTML", "URL" or "JS"
824               and HTML::Template will apply the specified escaping to all
825               variables unless they declare a different escape in the tem‐
826               plate.
827
828       param()
829
830       "param()" can be called in a number of ways
831
832       1) To return a list of parameters in the template :
833
834          my @parameter_names = $self->param();
835
836       2) To return the value set to a param :
837
838          my $value = $self->param('PARAM');
839
840       3) To set the value of a parameter :
841
842             # For simple TMPL_VARs:
843             $self->param(PARAM => 'value');
844
845             # with a subroutine reference that gets called to get the value
846             # of the scalar.  The sub will recieve the template object as a
847             # parameter.
848             $self->param(PARAM => sub { return 'value' });
849
850             # And TMPL_LOOPs:
851             $self->param(LOOP_PARAM =>
852                          [
853                           { PARAM => VALUE_FOR_FIRST_PASS, ... },
854                           { PARAM => VALUE_FOR_SECOND_PASS, ... }
855                           ...
856                          ]
857                         );
858
859       4) To set the value of a a number of parameters :
860
861            # For simple TMPL_VARs:
862            $self->param(PARAM => 'value',
863                         PARAM2 => 'value'
864                        );
865
866             # And with some TMPL_LOOPs:
867             $self->param(PARAM => 'value',
868                          PARAM2 => 'value',
869                          LOOP_PARAM =>
870                          [
871                           { PARAM => VALUE_FOR_FIRST_PASS, ... },
872                           { PARAM => VALUE_FOR_SECOND_PASS, ... }
873                           ...
874                          ],
875                          ANOTHER_LOOP_PARAM =>
876                          [
877                           { PARAM => VALUE_FOR_FIRST_PASS, ... },
878                           { PARAM => VALUE_FOR_SECOND_PASS, ... }
879                           ...
880                          ]
881                         );
882
883       5) To set the value of a a number of parameters using a hash-ref :
884
885             $self->param(
886                          {
887                             PARAM => 'value',
888                             PARAM2 => 'value',
889                             LOOP_PARAM =>
890                             [
891                               { PARAM => VALUE_FOR_FIRST_PASS, ... },
892                               { PARAM => VALUE_FOR_SECOND_PASS, ... }
893                               ...
894                             ],
895                             ANOTHER_LOOP_PARAM =>
896                             [
897                               { PARAM => VALUE_FOR_FIRST_PASS, ... },
898                               { PARAM => VALUE_FOR_SECOND_PASS, ... }
899                               ...
900                             ]
901                           }
902                          );
903
904       An error occurs if you try to set a value that is tainted if the
905       "force_untaint" option is set.
906
907       clear_params()
908
909       Sets all the parameters to undef.  Useful internally, if nowhere else!
910
911       output()
912
913       output() returns the final result of the template.  In most situations
914       you'll want to print this, like:
915
916          print $template->output();
917
918       When output is called each occurrence of <TMPL_VAR NAME=name> is
919       replaced with the value assigned to "name" via "param()".  If a named
920       parameter is unset it is simply replaced with ''.  <TMPL_LOOPS> are
921       evaluated once per parameter set, accumlating output on each pass.
922
923       Calling output() is guaranteed not to change the state of the Template
924       object, in case you were wondering.  This property is mostly important
925       for the internal implementation of loops.
926
927       You may optionally supply a filehandle to print to automatically as the
928       template is generated.  This may improve performance and lower memory
929       consumption.  Example:
930
931          $template->output(print_to => *STDOUT);
932
933       The return value is undefined when using the "print_to" option.
934
935       query()
936
937       This method allow you to get information about the template structure.
938       It can be called in a number of ways.  The simplest usage of query is
939       simply to check whether a parameter name exists in the template, using
940       the "name" option:
941
942         if ($template->query(name => 'foo')) {
943           # do something if a varaible of any type
944           # named FOO is in the template
945         }
946
947       This same usage returns the type of the parameter.  The type is the
948       same as the tag minus the leading 'TMPL_'.  So, for example, a TMPL_VAR
949       parameter returns 'VAR' from "query()".
950
951         if ($template->query(name => 'foo') eq 'VAR') {
952           # do something if FOO exists and is a TMPL_VAR
953         }
954
955       Note that the variables associated with TMPL_IFs and TMPL_UNLESSs will
956       be identified as 'VAR' unless they are also used in a TMPL_LOOP, in
957       which case they will return 'LOOP'.
958
959       "query()" also allows you to get a list of parameters inside a loop
960       (and inside loops inside loops).  Example loop:
961
962          <TMPL_LOOP NAME="EXAMPLE_LOOP">
963            <TMPL_VAR NAME="BEE">
964            <TMPL_VAR NAME="BOP">
965            <TMPL_LOOP NAME="EXAMPLE_INNER_LOOP">
966              <TMPL_VAR NAME="INNER_BEE">
967              <TMPL_VAR NAME="INNER_BOP">
968            </TMPL_LOOP>
969          </TMPL_LOOP>
970
971       And some query calls:
972
973         # returns 'LOOP'
974         $type = $template->query(name => 'EXAMPLE_LOOP');
975
976         # returns ('bop', 'bee', 'example_inner_loop')
977         @param_names = $template->query(loop => 'EXAMPLE_LOOP');
978
979         # both return 'VAR'
980         $type = $template->query(name => ['EXAMPLE_LOOP', 'BEE']);
981         $type = $template->query(name => ['EXAMPLE_LOOP', 'BOP']);
982
983         # and this one returns 'LOOP'
984         $type = $template->query(name => ['EXAMPLE_LOOP',
985                                           'EXAMPLE_INNER_LOOP']);
986
987         # and finally, this returns ('inner_bee', 'inner_bop')
988         @inner_param_names = $template->query(loop => ['EXAMPLE_LOOP',
989                                                        'EXAMPLE_INNER_LOOP']);
990
991         # for non existent parameter names you get undef
992         # this returns undef.
993         $type = $template->query(name => 'DWEAZLE_ZAPPA');
994
995         # calling loop on a non-loop parameter name will cause an error.
996         # this dies:
997         $type = $template->query(loop => 'DWEAZLE_ZAPPA');
998
999       As you can see above the "loop" option returns a list of parameter
1000       names and both "name" and "loop" take array refs in order to refer to
1001       parameters inside loops.  It is an error to use "loop" with a parameter
1002       that is not a loop.
1003
1004       Note that all the names are returned in lowercase and the types are
1005       uppercase.
1006
1007       Just like "param()", "query()" with no arguments returns all the param‐
1008       eter names in the template at the top level.
1009

FREQUENTLY ASKED QUESTIONS

1011       In the interest of greater understanding I've started a FAQ section of
1012       the perldocs.  Please look in here before you send me email.
1013
1014       1   Q: Is there a place to go to discuss HTML::Template and/or get
1015           help?
1016
1017           A: There's a mailing-list for discussing HTML::Template at
1018           html-template-users@lists.sourceforge.net.  To join:
1019
1020              http://lists.sourceforge.net/lists/listinfo/html-template-users
1021
1022           If you just want to get email when new releases are available you
1023           can join the announcements mailing-list here:
1024
1025              http://lists.sourceforge.net/lists/listinfo/html-template-announce
1026
1027       2   Q: Is there a searchable archive for the mailing-list?
1028
1029           A: Yes, you can find an archive of the SourceForge list here:
1030
1031             http://www.geocrawler.com/lists/3/SourceForge/23294/0/
1032
1033           For an archive of the old vm.com list, setup by Sean P. Scanlon,
1034           see:
1035
1036              http://bluedot.net/mail/archive/
1037
1038       3   Q: I want support for <TMPL_XXX>!  How about it?
1039
1040           A: Maybe.  I definitely encourage people to discuss their ideas for
1041           HTML::Template on the mailing list.  Please be ready to explain to
1042           me how the new tag fits in with HTML::Template's mission to provide
1043           a fast, lightweight system for using HTML templates.
1044
1045           NOTE: Offering to program said addition and provide it in the form
1046           of a patch to the most recent version of HTML::Template will defi‐
1047           nitely have a softening effect on potential opponents!
1048
1049       4   Q: I found a bug, can you fix it?
1050
1051           A: That depends.  Did you send me the VERSION of HTML::Template, a
1052           test script and a test template?  If so, then almost certainly.
1053
1054           If you're feeling really adventurous, HTML::Template has a publi‐
1055           cally available Subversion server.  See below for more information
1056           in the PUBLIC SUBVERSION SERVER section.
1057
1058       5   Q: <TMPL_VAR>s from the main template aren't working inside a
1059           <TMPL_LOOP>!  Why?
1060
1061           A: This is the intended behavior.  <TMPL_LOOP> introduces a sepa‐
1062           rate scope for <TMPL_VAR>s much like a subroutine call in Perl
1063           introduces a separate scope for "my" variables.
1064
1065           If you want your <TMPL_VAR>s to be global you can set the
1066           'global_vars' option when you call new().  See above for documenta‐
1067           tion of the 'global_vars' new() option.
1068
1069       6   Q: Why do you use /[Tt]/ instead of /t/i?  It's so ugly!
1070
1071           A: Simple - the case-insensitive match switch is very inefficient.
1072           According to _Mastering_Regular_Expressions_ from O'Reilly Press,
1073           /[Tt]/ is faster and more space efficient than /t/i - by as much as
1074           double against long strings.  //i essentially does a lc() on the
1075           string and keeps a temporary copy in memory.
1076
1077           When this changes, and it is in the 5.6 development series, I will
1078           gladly use //i.  Believe me, I realize [Tt] is hideously ugly.
1079
1080       7   Q: How can I pre-load my templates using cache-mode and mod_perl?
1081
1082           A: Add something like this to your startup.pl:
1083
1084              use HTML::Template;
1085              use File::Find;
1086
1087              print STDERR "Pre-loading HTML Templates...\n";
1088              find(
1089                   sub {
1090                     return unless /\.tmpl$/;
1091                     HTML::Template->new(
1092                                         filename => "$File::Find::dir/$_",
1093                                         cache => 1,
1094                                        );
1095                   },
1096                   '/path/to/templates',
1097                   '/another/path/to/templates/'
1098                 );
1099
1100           Note that you'll need to modify the "return unless" line to specify
1101           the extension you use for your template files - I use .tmpl, as you
1102           can see.  You'll also need to specify the path to your template
1103           files.
1104
1105           One potential problem: the "/path/to/templates/" must be EXACTLY
1106           the same path you use when you call HTML::Template->new().  Other‐
1107           wise the cache won't know they're the same file and will load a new
1108           copy - instead getting a speed increase, you'll double your memory
1109           usage.  To find out if this is happening set cache_debug => 1 in
1110           your application code and look for "CACHE MISS" messages in the
1111           logs.
1112
1113       8   Q: What characters are allowed in TMPL_* NAMEs?
1114
1115           A: Numbers, letters, '.', '/', '+', '-' and '_'.
1116
1117       9   Q: How can I execute a program from inside my template?
1118
1119           A: Short answer: you can't.  Longer answer: you shouldn't since
1120           this violates the fundamental concept behind HTML::Template - that
1121           design and code should be seperate.
1122
1123           But, inevitably some people still want to do it.  If that describes
1124           you then you should take a look at HTML::Template::Expr.  Using
1125           HTML::Template::Expr it should be easy to write a run_program()
1126           function.  Then you can do awful stuff like:
1127
1128             <tmpl_var expr="run_program('foo.pl')">
1129
1130           Just, please, don't tell me about it.  I'm feeling guilty enough
1131           just for writing HTML::Template::Expr in the first place.
1132
1133       10  Q: Can I get a copy of these docs in Japanese?
1134
1135           A: Yes you can.  See Kawai Takanori's translation at:
1136
1137              http://member.nifty.ne.jp/hippo2000/perltips/html/template.htm
1138
1139       11  Q: What's the best way to create a <select> form element using
1140           HTML::Template?
1141
1142           A: There is much disagreement on this issue.  My personal prefer‐
1143           ence is to use CGI.pm's excellent popup_menu() and scrolling_list()
1144           functions to fill in a single <tmpl_var select_foo> variable.
1145
1146           To some people this smacks of mixing HTML and code in a way that
1147           they hoped HTML::Template would help them avoid.  To them I'd say
1148           that HTML is a violation of the principle of separating design from
1149           programming.  There's no clear separation between the programmatic
1150           elements of the <form> tags and the layout of the <form> tags.
1151           You'll have to draw the line somewhere - clearly the designer can't
1152           be entirely in charge of form creation.
1153
1154           It's a balancing act and you have to weigh the pros and cons on
1155           each side.  It is certainly possible to produce a <select> element
1156           entirely inside the template.  What you end up with is a rat's nest
1157           of loops and conditionals.  Alternately you can give up a certain
1158           amount of flexibility in return for vastly simplifying your tem‐
1159           plates.  I generally choose the latter.
1160
1161           Another option is to investigate HTML::FillInForm which some have
1162           reported success using to solve this problem.
1163

BUGS

1165       I am aware of no bugs - if you find one, join the mailing list and tell
1166       us about it.  You can join the HTML::Template mailing-list by visiting:
1167
1168         http://lists.sourceforge.net/lists/listinfo/html-template-users
1169
1170       Of course, you can still email me directly (sam@tregar.com) with bugs,
1171       but I reserve the right to forward bug reports to the mailing list.
1172
1173       When submitting bug reports, be sure to include full details, including
1174       the VERSION of the module, a test script and a test template demon‐
1175       strating the problem!
1176
1177       If you're feeling really adventurous, HTML::Template has a publically
1178       available Subversion server.  See below for more information in the
1179       PUBLIC SUBVERSION SERVER section.
1180

CREDITS

1182       This module was the brain child of my boss, Jesse Erlbaum (
1183       jesse@vm.com ) at Vanguard Media ( http://vm.com ) .  The most original
1184       idea in this module - the <TMPL_LOOP> - was entirely his.
1185
1186       Fixes, Bug Reports, Optimizations and Ideas have been generously pro‐
1187       vided by:
1188
1189          Richard Chen
1190          Mike Blazer
1191          Adriano Nagelschmidt Rodrigues
1192          Andrej Mikus
1193          Ilya Obshadko
1194          Kevin Puetz
1195          Steve Reppucci
1196          Richard Dice
1197          Tom Hukins
1198          Eric Zylberstejn
1199          David Glasser
1200          Peter Marelas
1201          James William Carlson
1202          Frank D. Cringle
1203          Winfried Koenig
1204          Matthew Wickline
1205          Doug Steinwand
1206          Drew Taylor
1207          Tobias Brox
1208          Michael Lloyd
1209          Simran Gambhir
1210          Chris Houser <chouser@bluweb.com>
1211          Larry Moore
1212          Todd Larason
1213          Jody Biggs
1214          T.J. Mather
1215          Martin Schroth
1216          Dave Wolfe
1217          uchum
1218          Kawai Takanori
1219          Peter Guelich
1220          Chris Nokleberg
1221          Ralph Corderoy
1222          William Ward
1223          Ade Olonoh
1224          Mark Stosberg
1225          Lance Thomas
1226          Roland Giersig
1227          Jere Julian
1228          Peter Leonard
1229          Kenny Smith
1230          Sean P. Scanlon
1231          Martin Pfeffer
1232          David Ferrance
1233          Gyepi Sam
1234          Darren Chamberlain
1235          Paul Baker
1236          Gabor Szabo
1237          Craig Manley
1238          Richard Fein
1239          The Phalanx Project
1240          Sven Neuhaus
1241
1242       Thanks!
1243

WEBSITE

1245       You can find information about HTML::Template and other related modules
1246       at:
1247
1248          http://html-template.sourceforge.net
1249

PUBLIC SUBVERSION SERVER

1251       HTML::Template now has a publicly accessible Subversion server provided
1252       by SourceForge (www.sourceforge.net).  You can access it by going to
1253       http://sourceforge.net/svn/?group_id=1075.  Give it a try!
1254

AUTHOR

1256       Sam Tregar, sam@tregar.com
1257

LICENSE

1259         HTML::Template : A module for using HTML Templates with Perl
1260         Copyright (C) 2000-2002 Sam Tregar (sam@tregar.com)
1261
1262         This module is free software; you can redistribute it and/or modify it
1263         under the terms of either:
1264
1265         a) the GNU General Public License as published by the Free Software
1266         Foundation; either version 1, or (at your option) any later version,
1267
1268         or
1269
1270         b) the "Artistic License" which comes with this module.
1271
1272         This program is distributed in the hope that it will be useful,
1273         but WITHOUT ANY WARRANTY; without even the implied warranty of
1274         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either
1275         the GNU General Public License or the Artistic License for more details.
1276
1277         You should have received a copy of the Artistic License with this
1278         module, in the file ARTISTIC.  If not, I'll be glad to provide one.
1279
1280         You should have received a copy of the GNU General Public License
1281         along with this program; if not, write to the Free Software
1282         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
1283         USA
1284
1285
1286
1287perl v5.8.8                       2007-01-29                       Template(3)
Impressum