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
51       variables, loops and branches declared in the template.  This allows
52       you to separate design - the HTML - from the data, which you generate
53       in the 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
60       introductory 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
84       simplifies this situation considerably.  The designer can layout a
85       single row and the programmer can fill it in as many times as necessary
86       - all 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
91       better.  And it's pretty fast.
92

THE TAGS

94   TMPL_VAR
95         <TMPL_VAR NAME="PARAMETER_NAME">
96
97       The <TMPL_VAR> tag is very simple.  For each <TMPL_VAR> tag in the
98       template you call $template->param(PARAMETER_NAME => "VALUE").  When
99       the template is output the <TMPL_VAR> is replaced with the VALUE text
100       you specified.  If you don't set a parameter it just gets skipped in
101       the output.
102
103       Optionally you can use the "ESCAPE=HTML" option in the tag to indicate
104       that you want the value to be HTML-escaped before being returned from
105       output (the old ESCAPE=1 syntax is still supported).  This means that
106       the ", <, >, and & characters get translated into &quot;, &lt;, &gt;
107       and &amp; respectively.  This is useful when you want to use a TMPL_VAR
108       in a context where those characters would cause trouble.  Example:
109
110          <input name=param type=text value="<TMPL_VAR NAME="PARAM">">
111
112       If you called "param()" with a value like sam"my you'll get in trouble
113       with HTML's idea of a double-quote.  On the other hand, if you use
114       ESCAPE=HTML, like this:
115
116          <input name=param type=text value="<TMPL_VAR ESCAPE=HTML NAME="PARAM">">
117
118       You'll get what you wanted no matter what value happens to be passed in
119       for param.  You can also write ESCAPE="HTML", ESCAPE='HTML' and
120       ESCAPE='1'.
121
122       "ESCAPE=0" and "ESCAPE=NONE" turn off escaping, which is the default
123       behavior.
124
125       There is also the "ESCAPE=URL" option which may be used for VARs that
126       populate a URL.  It will do URL escaping, like replacing ' ' with '+'
127       and '/' with '%2F'.
128
129       There is also the "ESCAPE=JS" option which may be used for VARs that
130       need to be placed within a Javascript string. All \n, \r, ' and "
131       characters are escaped.
132
133       You can assign a default value to a variable with the DEFAULT
134       attribute.  For example, this will output "the devil gave me a taco" if
135       the "who" variable is not set.
136
137         The <TMPL_VAR NAME=WHO DEFAULT=devil> gave me a taco.
138
139   TMPL_LOOP
140         <TMPL_LOOP NAME="LOOP_NAME"> ... </TMPL_LOOP>
141
142       The <TMPL_LOOP> tag is a bit more complicated than <TMPL_VAR>.  The
143       <TMPL_LOOP> tag allows you to delimit a section of text and give it a
144       name.  Inside this named loop you place <TMPL_VAR>s.  Now you pass to
145       "param()" a list (an array ref) of parameter assignments (hash refs)
146       for this loop.  The loop iterates over the list and produces output
147       from the text block for each pass.  Unset parameters are skipped.
148       Here's an example:
149
150        In the template:
151
152          <TMPL_LOOP NAME=EMPLOYEE_INFO>
153             Name: <TMPL_VAR NAME=NAME> <br>
154             Job:  <TMPL_VAR NAME=JOB>  <p>
155          </TMPL_LOOP>
156
157
158        In the script:
159
160          $template->param(EMPLOYEE_INFO => [
161                                              { name => 'Sam', job => 'programmer' },
162                                              { name => 'Steve', job => 'soda jerk' },
163                                            ]
164                          );
165          print $template->output();
166
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
177       assignments and then iterates over the loop body producing output.
178
179       Often you'll want to generate a <TMPL_LOOP>'s contents
180       programmatically.  Here's an example of how this can be done (many
181       other ways are 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
242       visible within a template loop.  For the computer-science geeks among
243       you, a <TMPL_LOOP> introduces a new scope much like a perl subroutine
244       call.  If you want your variables to be global you can use
245       'global_vars' option to new() described below.
246
247   TMPL_INCLUDE
248         <TMPL_INCLUDE NAME="filename.tmpl">
249
250       This tag includes a template directly into the current template at the
251       point where the tag is found.  The included template contents are used
252       exactly as if its contents were physically included in the master
253       template.
254
255       The file specified can be an absolute path (beginning with a '/' under
256       Unix, for example).  If it isn't absolute, the path to the enclosing
257       file is tried first.  After that the path in the environment variable
258       HTML_TEMPLATE_ROOT is tried, if it exists.  Next, the "path" option is
259       consulted, first as-is and then with HTML_TEMPLATE_ROOT prepended if
260       available.  As a final attempt, the filename is passed to open()
261       directly.  See below for more information on HTML_TEMPLATE_ROOT and the
262       "path" option to new().
263
264       As a protection against infinitly recursive includes, an arbitary limit
265       of 10 levels deep is imposed.  You can alter this limit with the
266       "max_includes" option.  See the entry for the "max_includes" option
267       below for more details.
268
269   TMPL_IF
270         <TMPL_IF NAME="PARAMETER_NAME"> ... </TMPL_IF>
271
272       The <TMPL_IF> tag allows you to include or not include a block of the
273       template based on the value of a given parameter name.  If the
274       parameter is given a value that is true for Perl - like '1' - then the
275       block is included in the output.  If it is not defined, or given a
276       false value - like '0' - then it is skipped.  The parameters are
277       specified the same way as with TMPL_VAR.
278
279       Example Template:
280
281          <TMPL_IF NAME="BOOL">
282            Some text that only gets displayed if BOOL is true!
283          </TMPL_IF>
284
285       Now if you call $template->param(BOOL => 1) then the above block will
286       be included by output.
287
288       <TMPL_IF> </TMPL_IF> blocks can include any valid HTML::Template
289       construct - VARs and LOOPs and other IF/ELSE blocks.  Note, however,
290       that intersecting a <TMPL_IF> and a <TMPL_LOOP> is invalid.
291
292          Not going to work:
293          <TMPL_IF BOOL>
294             <TMPL_LOOP SOME_LOOP>
295          </TMPL_IF>
296             </TMPL_LOOP>
297
298       If the name of a TMPL_LOOP is used in a TMPL_IF, the IF block will
299       output if the loop has at least one row.  Example:
300
301         <TMPL_IF LOOP_ONE>
302           This will output if the loop is not empty.
303         </TMPL_IF>
304
305         <TMPL_LOOP LOOP_ONE>
306           ....
307         </TMPL_LOOP>
308
309       WARNING: Much of the benefit of HTML::Template is in decoupling your
310       Perl and HTML.  If you introduce numerous cases where you have TMPL_IFs
311       and matching Perl if()s, you will create a maintenance problem in
312       keeping the two synchronized.  I suggest you adopt the practice of only
313       using TMPL_IF if you can do so without requiring a matching if() in
314       your Perl code.
315
316   TMPL_ELSE
317         <TMPL_IF NAME="PARAMETER_NAME"> ... <TMPL_ELSE> ... </TMPL_IF>
318
319       You can include an alternate block in your TMPL_IF block by using
320       TMPL_ELSE.  NOTE: You still end the block with </TMPL_IF>, not
321       </TMPL_ELSE>!
322
323          Example:
324
325          <TMPL_IF BOOL>
326            Some text that is included only if BOOL is true
327          <TMPL_ELSE>
328            Some text that is included only if BOOL is false
329          </TMPL_IF>
330
331   TMPL_UNLESS
332         <TMPL_UNLESS NAME="PARAMETER_NAME"> ... </TMPL_UNLESS>
333
334       This tag is the opposite of <TMPL_IF>.  The block is output if the
335       CONTROL_PARAMETER is set false or not defined.  You can use <TMPL_ELSE>
336       with <TMPL_UNLESS> just as you can with <TMPL_IF>.
337
338         Example:
339
340         <TMPL_UNLESS BOOL>
341           Some text that is output only if BOOL is FALSE.
342         <TMPL_ELSE>
343           Some text that is output only if BOOL is TRUE.
344         </TMPL_UNLESS>
345
346       If the name of a TMPL_LOOP is used in a TMPL_UNLESS, the UNLESS block
347       output if the loop has zero rows.
348
349         <TMPL_UNLESS LOOP_ONE>
350           This will output if the loop is empty.
351         </TMPL_UNLESS>
352
353         <TMPL_LOOP LOOP_ONE>
354           ....
355         </TMPL_LOOP>
356
357   NOTES
358       HTML::Template's tags are meant to mimic normal HTML tags.  However,
359       they are allowed to "break the rules".  Something like:
360
361          <img src="<TMPL_VAR IMAGE_SRC>">
362
363       is not really valid HTML, but it is a perfectly valid use and will work
364       as planned.
365
366       The "NAME=" in the tag is optional, although for extensibility's sake I
367       recommend using it.  Example - "<TMPL_LOOP LOOP_NAME>" is acceptable.
368
369       If you're a fanatic about valid HTML and would like your templates to
370       conform to valid HTML syntax, you may optionally type template tags in
371       the form of HTML comments. This may be of use to HTML authors who would
372       like to validate their templates' HTML syntax prior to HTML::Template
373       processing, or who use DTD-savvy editing tools.
374
375         <!-- TMPL_VAR NAME=PARAM1 -->
376
377       In order to realize a dramatic savings in bandwidth, the standard (non-
378       comment) tags will be used throughout this documentation.
379

METHODS

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

FREQUENTLY ASKED QUESTIONS

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

BUGS

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

CREDITS

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

WEBSITE

1238       You can find information about HTML::Template and other related modules
1239       at:
1240
1241          http://html-template.sourceforge.net
1242

PUBLIC SUBVERSION SERVER

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

AUTHOR

1249       Sam Tregar, sam@tregar.com
1250

LICENSE

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

POD ERRORS

1279       Hey! The above document had some coding errors, which are explained
1280       below:
1281
1282       Around line 905:
1283           =back doesn't take any parameters, but you said =back 4
1284
1285
1286
1287perl v5.12.0                      2007-01-29                       Template(3)
Impressum