1HTML::Template(3) User Contributed Perl Documentation HTML::Template(3)
2
3
4
6 HTML::Template - Perl module to use HTML-like templating language
7
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></head>
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 you can use it in 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
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
48 "<TMPL_UNLESS>". The file written with HTML and these new tags is
49 called a template. It is usually saved separate from your script -
50 possibly even created by someone else! Using this module you fill in
51 the values for the variables, loops and branches declared in the
52 template. This allows you to separate design - the HTML - from the
53 data, which you generate in the Perl script.
54
55 This module is licensed under the same terms as Perl. See the LICENSE
56 section below for more details.
57
59 If you're new to HTML::Template, I suggest you start with the
60 introductory article available on Perl Monks:
61
62 http://www.perlmonks.org/?node_id=65642
63
65 Please see HTML::Template::FAQ
66
68 It is true that there are a number of packages out there to do HTML
69 templates. On the one hand you have things like HTML::Embperl which
70 allows you freely mix Perl with HTML. On the other hand lie home-grown
71 variable substitution solutions. Hopefully the module can find a place
72 between the two.
73
74 One advantage of this module over a full HTML::Embperl-esque solution
75 is that it enforces an important divide - design and programming. By
76 limiting the programmer to just using simple variables and loops in the
77 HTML, the template remains accessible to designers and other non-perl
78 people. The use of HTML-esque syntax goes further to make the format
79 understandable to others. In the future this similarity could be used
80 to extend existing HTML editors/analyzers to support HTML::Template.
81
82 An advantage of this module over home-grown tag-replacement schemes is
83 the support for loops. In my work I am often called on to produce
84 tables of data in html. Producing them using simplistic HTML templates
85 results in programs containing lots of HTML since the HTML itself
86 cannot represent loops. The introduction of loop statements in the
87 HTML simplifies this situation considerably. The designer can layout a
88 single row and the programmer can fill it in as many times as necessary
89 - all they must agree on is the parameter names.
90
91 For all that, I think the best thing about this module is that it does
92 just one thing and it does it quickly and carefully. It doesn't try to
93 replace Perl and HTML, it just augments them to interact a little
94 better. And it's pretty fast.
95
97 TMPL_VAR
98 <TMPL_VAR NAME="PARAMETER_NAME">
99
100 The "<TMPL_VAR>" tag is very simple. For each "<TMPL_VAR>" tag in the
101 template you call:
102
103 $template->param(PARAMETER_NAME => "VALUE")
104
105 When the template is output the "<TMPL_VAR>" is replaced with the VALUE
106 text you specified. If you don't set a parameter it just gets skipped
107 in the output.
108
109 You can also specify the value of the parameter as a code reference in
110 order to have "lazy" variables. These sub routines will only be
111 referenced if the variables are used. See "LAZY VALUES" for more
112 information.
113
114 Attributes
115
116 The following "attributes" can also be specified in template var tags:
117
118 • escape
119
120 This allows you to escape the value before it's put into the
121 output.
122
123 This is useful when you want to use a TMPL_VAR in a context where
124 those characters would cause trouble. For example:
125
126 <input name=param type=text value="<TMPL_VAR PARAM>">
127
128 If you called param() with a value like "sam"my" you'll get in
129 trouble with HTML's idea of a double-quote. On the other hand, if
130 you use "escape=html", like this:
131
132 <input name=param type=text value="<TMPL_VAR PARAM ESCAPE=HTML>">
133
134 You'll get what you wanted no matter what value happens to be
135 passed in for param.
136
137 The following escape values are supported:
138
139 • html
140
141 Replaces the following characters with their HTML entity
142 equivalent: "&", """, "'", "<", ">"
143
144 • js
145
146 Escapes (with a backslash) the following characters: "\", "'",
147 """, "\n", "\r"
148
149 • url
150
151 URL escapes any ASCII characters except for letters, numbers,
152 "_", "." and "-".
153
154 • none
155
156 Performs no escaping. This is the default, but it's useful to
157 be able to explicitly turn off escaping if you are using the
158 "default_escape" option.
159
160 • default
161
162 With this attribute you can assign a default value to a variable.
163 For example, this will output "the devil gave me a taco" if the
164 "who" variable is not set.
165
166 <TMPL_VAR WHO DEFAULT="the devil"> gave me a taco.
167
168 TMPL_LOOP
169 <TMPL_LOOP NAME="LOOP_NAME"> ... </TMPL_LOOP>
170
171 The "<TMPL_LOOP>" tag is a bit more complicated than "<TMPL_VAR>". The
172 "<TMPL_LOOP>" tag allows you to delimit a section of text and give it a
173 name. Inside this named loop you place "<TMPL_VAR>"s. Now you pass to
174 param() a list (an array ref) of parameter assignments (hash refs) for
175 this loop. The loop iterates over the list and produces output from
176 the text block for each pass. Unset parameters are skipped. Here's an
177 example:
178
179 In the template:
180
181 <TMPL_LOOP NAME=EMPLOYEE_INFO>
182 Name: <TMPL_VAR NAME=NAME> <br>
183 Job: <TMPL_VAR NAME=JOB> <p>
184 </TMPL_LOOP>
185
186 In your Perl code:
187
188 $template->param(
189 EMPLOYEE_INFO => [{name => 'Sam', job => 'programmer'}, {name => 'Steve', job => 'soda jerk'}]
190 );
191 print $template->output();
192
193 The output is:
194
195 Name: Sam
196 Job: programmer
197
198 Name: Steve
199 Job: soda jerk
200
201 As you can see above the "<TMPL_LOOP>" takes a list of variable
202 assignments and then iterates over the loop body producing output.
203
204 Often you'll want to generate a "<TMPL_LOOP>"'s contents
205 programmatically. Here's an example of how this can be done (many
206 other ways are possible!):
207
208 # a couple of arrays of data to put in a loop:
209 my @words = qw(I Am Cool);
210 my @numbers = qw(1 2 3);
211 my @loop_data = (); # initialize an array to hold your loop
212
213 while (@words and @numbers) {
214 my %row_data; # get a fresh hash for the row data
215
216 # fill in this row
217 $row_data{WORD} = shift @words;
218 $row_data{NUMBER} = shift @numbers;
219
220 # the crucial step - push a reference to this row into the loop!
221 push(@loop_data, \%row_data);
222 }
223
224 # finally, assign the loop data to the loop param, again with a reference:
225 $template->param(THIS_LOOP => \@loop_data);
226
227 The above example would work with a template like:
228
229 <TMPL_LOOP NAME="THIS_LOOP">
230 Word: <TMPL_VAR NAME="WORD">
231 Number: <TMPL_VAR NAME="NUMBER">
232
233 </TMPL_LOOP>
234
235 It would produce output like:
236
237 Word: I
238 Number: 1
239
240 Word: Am
241 Number: 2
242
243 Word: Cool
244 Number: 3
245
246 "<TMPL_LOOP>"s within "<TMPL_LOOP>"s are fine and work as you would
247 expect. If the syntax for the param() call has you stumped, here's an
248 example of a param call with one nested loop:
249
250 $template->param(
251 LOOP => [
252 {
253 name => 'Bobby',
254 nicknames => [{name => 'the big bad wolf'}, {name => 'He-Man'}],
255 },
256 ],
257 );
258
259 Basically, each "<TMPL_LOOP>" gets an array reference. Inside the
260 array are any number of hash references. These hashes contain the
261 name=>value pairs for a single pass over the loop template.
262
263 Inside a "<TMPL_LOOP>", the only variables that are usable are the ones
264 from the "<TMPL_LOOP>". The variables in the outer blocks are not
265 visible within a template loop. For the computer-science geeks among
266 you, a "<TMPL_LOOP>" introduces a new scope much like a perl subroutine
267 call. If you want your variables to be global you can use
268 "global_vars" option to new() described below.
269
270 TMPL_INCLUDE
271 <TMPL_INCLUDE NAME="filename.tmpl">
272
273 This tag includes a template directly into the current template at the
274 point where the tag is found. The included template contents are used
275 exactly as if its contents were physically included in the master
276 template.
277
278 The file specified can be an absolute path (beginning with a '/' under
279 Unix, for example). If it isn't absolute, the path to the enclosing
280 file is tried first. After that the path in the environment variable
281 "HTML_TEMPLATE_ROOT" is tried, if it exists. Next, the "path" option
282 is consulted, first as-is and then with "HTML_TEMPLATE_ROOT" prepended
283 if available. As a final attempt, the filename is passed to open()
284 directly. See below for more information on "HTML_TEMPLATE_ROOT" and
285 the "path" option to new().
286
287 As a protection against infinitely recursive includes, an arbitrary
288 limit of 10 levels deep is imposed. You can alter this limit with the
289 "max_includes" option. See the entry for the "max_includes" option
290 below for more details.
291
292 TMPL_IF
293 <TMPL_IF NAME="PARAMETER_NAME"> ... </TMPL_IF>
294
295 The "<TMPL_IF>" tag allows you to include or not include a block of the
296 template based on the value of a given parameter name. If the
297 parameter is given a value that is true for Perl - like '1' - then the
298 block is included in the output. If it is not defined, or given a
299 false value - like '0' - then it is skipped. The parameters are
300 specified the same way as with "<TMPL_VAR>".
301
302 Example Template:
303
304 <TMPL_IF NAME="BOOL">
305 Some text that only gets displayed if BOOL is true!
306 </TMPL_IF>
307
308 Now if you call "$template->param(BOOL => 1)" then the above block will
309 be included by output.
310
311 "<TMPL_IF> </TMPL_IF>" blocks can include any valid HTML::Template
312 construct - "VAR"s and "LOOP"s and other "IF"/"ELSE" blocks. Note,
313 however, that intersecting a "<TMPL_IF>" and a "<TMPL_LOOP>" is
314 invalid.
315
316 Not going to work:
317 <TMPL_IF BOOL>
318 <TMPL_LOOP SOME_LOOP>
319 </TMPL_IF>
320 </TMPL_LOOP>
321
322 If the name of a "<TMPL_LOOP>" is used in a "<TMPL_IF>", the "IF" block
323 will output if the loop has at least one row. Example:
324
325 <TMPL_IF LOOP_ONE>
326 This will output if the loop is not empty.
327 </TMPL_IF>
328
329 <TMPL_LOOP LOOP_ONE>
330 ....
331 </TMPL_LOOP>
332
333 WARNING: Much of the benefit of HTML::Template is in decoupling your
334 Perl and HTML. If you introduce numerous cases where you have
335 "TMPL_IF"s and matching Perl "if"s, you will create a maintenance
336 problem in keeping the two synchronized. I suggest you adopt the
337 practice of only using "TMPL_IF" if you can do so without requiring a
338 matching "if" in your Perl code.
339
340 TMPL_ELSE
341 <TMPL_IF NAME="PARAMETER_NAME"> ... <TMPL_ELSE> ... </TMPL_IF>
342
343 You can include an alternate block in your "<TMPL_IF>" block by using
344 "<TMPL_ELSE>". NOTE: You still end the block with "</TMPL_IF>", not
345 "</TMPL_ELSE>"!
346
347 Example:
348 <TMPL_IF BOOL>
349 Some text that is included only if BOOL is true
350 <TMPL_ELSE>
351 Some text that is included only if BOOL is false
352 </TMPL_IF>
353
354 TMPL_UNLESS
355 <TMPL_UNLESS NAME="PARAMETER_NAME"> ... </TMPL_UNLESS>
356
357 This tag is the opposite of "<TMPL_IF>". The block is output if the
358 "PARAMETER_NAME" is set false or not defined. You can use
359 "<TMPL_ELSE>" with "<TMPL_UNLESS>" just as you can with "<TMPL_IF>".
360
361 Example:
362 <TMPL_UNLESS BOOL>
363 Some text that is output only if BOOL is FALSE.
364 <TMPL_ELSE>
365 Some text that is output only if BOOL is TRUE.
366 </TMPL_UNLESS>
367
368 If the name of a "<TMPL_LOOP>" is used in a "<TMPL_UNLESS>", the
369 "<UNLESS>" block output if the loop has zero rows.
370
371 <TMPL_UNLESS LOOP_ONE>
372 This will output if the loop is empty.
373 </TMPL_UNLESS>
374
375 <TMPL_LOOP LOOP_ONE>
376 ....
377 </TMPL_LOOP>
378
379 NOTES
380 HTML::Template's tags are meant to mimic normal HTML tags. However,
381 they are allowed to "break the rules". Something like:
382
383 <img src="<TMPL_VAR IMAGE_SRC>">
384
385 is not really valid HTML, but it is a perfectly valid use and will work
386 as planned.
387
388 The "NAME=" in the tag is optional, although for extensibility's sake I
389 recommend using it. Example - "<TMPL_LOOP LOOP_NAME>" is acceptable.
390
391 If you're a fanatic about valid HTML and would like your templates to
392 conform to valid HTML syntax, you may optionally type template tags in
393 the form of HTML comments. This may be of use to HTML authors who would
394 like to validate their templates' HTML syntax prior to HTML::Template
395 processing, or who use DTD-savvy editing tools.
396
397 <!-- TMPL_VAR NAME=PARAM1 -->
398
399 In order to realize a dramatic savings in bandwidth, the standard (non-
400 comment) tags will be used throughout this documentation.
401
403 new
404 Call new() to create a new Template object:
405
406 my $template = HTML::Template->new(
407 filename => 'file.tmpl',
408 option => 'value',
409 );
410
411 You must call new() with at least one "name =" value> pair specifying
412 how to access the template text. You can use "filename => 'file.tmpl'"
413 to specify a filename to be opened as the template. Alternately you
414 can use:
415
416 my $t = HTML::Template->new(
417 scalarref => $ref_to_template_text,
418 option => 'value',
419 );
420
421 and
422
423 my $t = HTML::Template->new(
424 arrayref => $ref_to_array_of_lines,
425 option => 'value',
426 );
427
428 These initialize the template from in-memory resources. In almost
429 every case you'll want to use the filename parameter. If you're
430 worried about all the disk access from reading a template file just use
431 mod_perl and the cache option detailed below.
432
433 You can also read the template from an already opened filehandle,
434 either traditionally as a glob or as a FileHandle:
435
436 my $t = HTML::Template->new(filehandle => *FH, option => 'value');
437
438 The four new() calling methods can also be accessed as below, if you
439 prefer.
440
441 my $t = HTML::Template->new_file('file.tmpl', option => 'value');
442
443 my $t = HTML::Template->new_scalar_ref($ref_to_template_text, option => 'value');
444
445 my $t = HTML::Template->new_array_ref($ref_to_array_of_lines, option => 'value');
446
447 my $t = HTML::Template->new_filehandle($fh, option => 'value');
448
449 And as a final option, for those that might prefer it, you can call new
450 as:
451
452 my $t = HTML::Template->new(
453 type => 'filename',
454 source => 'file.tmpl',
455 );
456
457 Which works for all three of the source types.
458
459 If the environment variable "HTML_TEMPLATE_ROOT" is set and your
460 filename doesn't begin with "/", then the path will be relative to the
461 value of c<HTML_TEMPLATE_ROOT>.
462
463 Example - if the environment variable "HTML_TEMPLATE_ROOT" is set to
464 /home/sam and I call "HTML::Template->new()" with filename set to
465 "sam.tmpl", HTML::Template will try to open /home/sam/sam.tmpl to
466 access the template file. You can also affect the search path for
467 files with the "path" option to new() - see below for more information.
468
469 You can modify the Template object's behavior with new(). The options
470 are available:
471
472 Error Detection Options
473
474 • die_on_bad_params
475
476 If set to 0 the module will let you call:
477
478 $template->param(param_name => 'value')
479
480 even if 'param_name' doesn't exist in the template body. Defaults
481 to 1.
482
483 • force_untaint
484
485 If set to 1 the module will not allow you to set unescaped
486 parameters with tainted values. If set to 2 you will have to
487 untaint all parameters, including ones with the escape attribute.
488 This option makes sure you untaint everything so you don't
489 accidentally introduce e.g. cross-site-scripting (XSS)
490 vulnerabilities. Requires taint mode. Defaults to 0.
491
492 • strict - if set to 0 the module will allow things that look like
493 they might be TMPL_* tags to get by without dieing. Example:
494
495 <TMPL_HUH NAME=ZUH>
496
497 Would normally cause an error, but if you call new with "strict =>
498 0" HTML::Template will ignore it. Defaults to 1.
499
500 • vanguard_compatibility_mode
501
502 If set to 1 the module will expect to see "<TMPL_VAR>"s that look
503 like "%NAME%" in addition to the standard syntax. Also sets
504 "die_on_bad_params =" 0>. If you're not at Vanguard Media trying
505 to use an old format template don't worry about this one. Defaults
506 to 0.
507
508 Caching Options
509
510 • cache
511
512 If set to 1 the module will cache in memory the parsed templates
513 based on the filename parameter, the modification date of the file
514 and the options passed to new(). This only applies to templates
515 opened with the filename parameter specified, not scalarref or
516 arrayref templates. Caching also looks at the modification times
517 of any files included using "<TMPL_INCLUDE>" tags, but again, only
518 if the template is opened with filename parameter.
519
520 This is mainly of use in a persistent environment like
521 Apache/mod_perl. It has absolutely no benefit in a normal CGI
522 environment since the script is unloaded from memory after every
523 request. For a cache that does work for a non-persistent
524 environment see the "shared_cache" option below.
525
526 My simplistic testing shows that using cache yields a 90%
527 performance increase under mod_perl. Cache defaults to 0.
528
529 • shared_cache
530
531 If set to 1 the module will store its cache in shared memory using
532 the IPC::SharedCache module (available from CPAN). The effect of
533 this will be to maintain a single shared copy of each parsed
534 template for all instances of HTML::Template on the same machine to
535 use. This can be a significant reduction in memory usage in an
536 environment with a single machine but multiple servers. As an
537 example, on one of our systems we use 4MB of template cache and
538 maintain 25 httpd processes - shared_cache results in saving almost
539 100MB! Of course, some reduction in speed versus normal caching is
540 to be expected. Another difference between normal caching and
541 shared_cache is that shared_cache will work in a non-persistent
542 environment (like normal CGI) - normal caching is only useful in a
543 persistent environment like Apache/mod_perl.
544
545 By default HTML::Template uses the IPC key 'TMPL' as a shared root
546 segment (0x4c504d54 in hex), but this can be changed by setting the
547 "ipc_key" new() parameter to another 4-character or integer key.
548 Other options can be used to affect the shared memory cache
549 correspond to IPC::SharedCache options - "ipc_mode",
550 "ipc_segment_size" and "ipc_max_size". See IPC::SharedCache for a
551 description of how these work - in most cases you shouldn't need to
552 change them from the defaults.
553
554 For more information about the shared memory cache system used by
555 HTML::Template see IPC::SharedCache.
556
557 • double_cache
558
559 If set to 1 the module will use a combination of "shared_cache" and
560 normal cache mode for the best possible caching. Of course, it
561 also uses the most memory of all the cache modes. All the same
562 ipc_* options that work with "shared_cache" apply to "double_cache"
563 as well. Defaults to 0.
564
565 • blind_cache
566
567 If set to 1 the module behaves exactly as with normal caching but
568 does not check to see if the file has changed on each request.
569 This option should be used with caution, but could be of use on
570 high-load servers. My tests show "blind_cache" performing only 1
571 to 2 percent faster than cache under mod_perl.
572
573 NOTE: Combining this option with shared_cache can result in stale
574 templates stuck permanently in shared memory!
575
576 • file_cache
577
578 If set to 1 the module will store its cache in a file using the
579 Storable module. It uses no additional memory, and my simplistic
580 testing shows that it yields a 50% performance advantage. Like
581 "shared_cache", it will work in a non-persistent environments (like
582 CGI). Default is 0.
583
584 If you set this option you must set the "file_cache_dir" option.
585 See below for details.
586
587 NOTE: Storable uses flock() to ensure safe access to cache files.
588 Using "file_cache" on a system or filesystem (like NFS) without
589 flock() support is dangerous.
590
591 • file_cache_dir
592
593 Sets the directory where the module will store the cache files if
594 "file_cache" is enabled. Your script will need write permissions
595 to this directory. You'll also need to make sure the sufficient
596 space is available to store the cache files.
597
598 • file_cache_dir_mode
599
600 Sets the file mode for newly created "file_cache" directories and
601 subdirectories. Defaults to "0700" for security but this may be
602 inconvenient if you do not have access to the account running the
603 webserver.
604
605 • double_file_cache
606
607 If set to 1 the module will use a combination of "file_cache" and
608 normal "cache" mode for the best possible caching. The
609 file_cache_* options that work with file_cache apply to
610 "double_file_cache" as well. Defaults to 0.
611
612 • cache_lazy_vars
613
614 The option tells HTML::Template to cache the values returned from
615 code references used for "TMPL_VAR"s. See "LAZY VALUES" for
616 details.
617
618 • cache_lazy_loops
619
620 The option tells HTML::Template to cache the values returned from
621 code references used for "TMPL_LOOP"s. See "LAZY VALUES" for
622 details.
623
624 Filesystem Options
625
626 • path
627
628 You can set this variable with a list of paths to search for files
629 specified with the "filename" option to new() and for files
630 included with the "<TMPL_INCLUDE>" tag. This list is only
631 consulted when the filename is relative. The "HTML_TEMPLATE_ROOT"
632 environment variable is always tried first if it exists. Also, if
633 "HTML_TEMPLATE_ROOT" is set then an attempt will be made to prepend
634 "HTML_TEMPLATE_ROOT" onto paths in the path array. In the case of
635 a "<TMPL_INCLUDE>" file, the path to the including file is also
636 tried before path is consulted.
637
638 Example:
639
640 my $template = HTML::Template->new(
641 filename => 'file.tmpl',
642 path => ['/path/to/templates', '/alternate/path'],
643 );
644
645 NOTE: the paths in the path list must be expressed as UNIX paths,
646 separated by the forward-slash character ('/').
647
648 • search_path_on_include
649
650 If set to a true value the module will search from the top of the
651 array of paths specified by the path option on every
652 "<TMPL_INCLUDE>" and use the first matching template found. The
653 normal behavior is to look only in the current directory for a
654 template to include. Defaults to 0.
655
656 • utf8
657
658 Setting this to true tells HTML::Template to treat your template
659 files as UTF-8 encoded. This will apply to any file's passed to
660 new() or any included files. It won't do anything special to
661 scalars templates passed to new() since you should be doing the
662 encoding on those yourself.
663
664 my $template = HTML::Template->new(
665 filename => 'umlauts_are_awesome.tmpl',
666 utf8 => 1,
667 );
668
669 Most templates are either ASCII (the default) or UTF-8 encoded
670 Unicode. But if you need some other encoding other than these 2,
671 look at the "open_mode" option.
672
673 NOTE: The "utf8" and "open_mode" options cannot be used at the same
674 time.
675
676 • open_mode
677
678 You can set this option to an opening mode with which all template
679 files will be opened.
680
681 For example, if you want to use a template that is UTF-16 encoded
682 unicode:
683
684 my $template = HTML::Template->new(
685 filename => 'file.tmpl',
686 open_mode => '<:encoding(UTF-16)',
687 );
688
689 That way you can force a different encoding (than the default ASCII
690 or UTF-8), CR/LF properties etc. on the template files. See PerlIO
691 for details.
692
693 NOTE: this only works in perl 5.7.1 and above.
694
695 NOTE: you have to supply an opening mode that actually permits
696 reading from the file handle.
697
698 NOTE: The "utf8" and "open_mode" options cannot be used at the same
699 time.
700
701 Debugging Options
702
703 • debug
704
705 If set to 1 the module will write random debugging information to
706 STDERR. Defaults to 0.
707
708 • stack_debug
709
710 If set to 1 the module will use Data::Dumper to print out the
711 contents of the parse_stack to STDERR. Defaults to 0.
712
713 • cache_debug
714
715 If set to 1 the module will send information on cache loads, hits
716 and misses to STDERR. Defaults to 0.
717
718 • shared_cache_debug
719
720 If set to 1 the module will turn on the debug option in
721 IPC::SharedCache. Defaults to 0.
722
723 • memory_debug
724
725 If set to 1 the module will send information on cache memory usage
726 to STDERR. Requires the GTop module. Defaults to 0.
727
728 Miscellaneous Options
729
730 • associate
731
732 This option allows you to inherit the parameter values from other
733 objects. The only requirement for the other object is that it have
734 a param() method that works like HTML::Template's param(). A good
735 candidate would be a CGI query object. Example:
736
737 my $query = CGI->new;
738 my $template = HTML::Template->new(
739 filename => 'template.tmpl',
740 associate => $query,
741 );
742
743 Now, "$template->output()" will act as though
744
745 $template->param(form_field => $cgi->param('form_field'));
746
747 had been specified for each key/value pair that would be provided
748 by the "$cgi->param()" method. Parameters you set directly take
749 precedence over associated parameters.
750
751 You can specify multiple objects to associate by passing an
752 anonymous array to the associate option. They are searched for
753 parameters in the order they appear:
754
755 my $template = HTML::Template->new(
756 filename => 'template.tmpl',
757 associate => [$query, $other_obj],
758 );
759
760 NOTE: The parameter names are matched in a case-insensitive manner.
761 If you have two parameters in a CGI object like 'NAME' and 'Name'
762 one will be chosen randomly by associate. This behavior can be
763 changed by the "case_sensitive" option.
764
765 • case_sensitive
766
767 Setting this option to true causes HTML::Template to treat template
768 variable names case-sensitively. The following example would only
769 set one parameter without the "case_sensitive" option:
770
771 my $template = HTML::Template->new(
772 filename => 'template.tmpl',
773 case_sensitive => 1
774 );
775 $template->param(
776 FieldA => 'foo',
777 fIELDa => 'bar',
778 );
779
780 This option defaults to off.
781
782 NOTE: with "case_sensitive" and "loop_context_vars" the special
783 loop variables are available in lower-case only.
784
785 • loop_context_vars
786
787 When this parameter is set to true (it is false by default) extra
788 variables that depend on the loop's context are made available
789 inside a loop. These are:
790
791 • __first__
792
793 Value that is true for the first iteration of the loop and
794 false every other time.
795
796 • __last__
797
798 Value that is true for the last iteration of the loop and false
799 every other time.
800
801 • __inner__
802
803 Value that is true for the every iteration of the loop except
804 for the first and last.
805
806 • __outer__
807
808 Value that is true for the first and last iterations of the
809 loop.
810
811 • __odd__
812
813 Value that is true for the every odd iteration of the loop.
814
815 • __even__
816
817 Value that is true for the every even iteration of the loop.
818
819 • __counter__
820
821 An integer (starting from 1) whose value increments for each
822 iteration of the loop.
823
824 • __index__
825
826 An integer (starting from 0) whose value increments for each
827 iteration of the loop.
828
829 Just like any other "TMPL_VAR"s these variables can be used in
830 "<TMPL_IF>", "<TMPL_UNLESS>" and "<TMPL_ELSE>" to control how a
831 loop is output.
832
833 Example:
834
835 <TMPL_LOOP NAME="FOO">
836 <TMPL_IF NAME="__first__">
837 This only outputs on the first pass.
838 </TMPL_IF>
839
840 <TMPL_IF NAME="__odd__">
841 This outputs every other pass, on the odd passes.
842 </TMPL_IF>
843
844 <TMPL_UNLESS NAME="__odd__">
845 This outputs every other pass, on the even passes.
846 </TMPL_UNLESS>
847
848 <TMPL_IF NAME="__inner__">
849 This outputs on passes that are neither first nor last.
850 </TMPL_IF>
851
852 This is pass number <TMPL_VAR NAME="__counter__">.
853
854 <TMPL_IF NAME="__last__">
855 This only outputs on the last pass.
856 </TMPL_IF>
857 </TMPL_LOOP>
858
859 One use of this feature is to provide a "separator" similar in
860 effect to the perl function join(). Example:
861
862 <TMPL_LOOP FRUIT>
863 <TMPL_IF __last__> and </TMPL_IF>
864 <TMPL_VAR KIND><TMPL_UNLESS __last__>, <TMPL_ELSE>.</TMPL_UNLESS>
865 </TMPL_LOOP>
866
867 Would output something like:
868
869 Apples, Oranges, Brains, Toes, and Kiwi.
870
871 Given an appropriate param() call, of course. NOTE: A loop with
872 only a single pass will get both "__first__" and "__last__" set to
873 true, but not "__inner__".
874
875 • no_includes
876
877 Set this option to 1 to disallow the "<TMPL_INCLUDE>" tag in the
878 template file. This can be used to make opening untrusted
879 templates slightly less dangerous. Defaults to 0.
880
881 • max_includes
882
883 Set this variable to determine the maximum depth that includes can
884 reach. Set to 10 by default. Including files to a depth greater
885 than this value causes an error message to be displayed. Set to 0
886 to disable this protection.
887
888 • die_on_missing_include
889
890 If true, then HTML::Template will die if it can't find a file for a
891 "<TMPL_INCLUDE>". This defaults to true.
892
893 • global_vars
894
895 Normally variables declared outside a loop are not available inside
896 a loop. This option makes "<TMPL_VAR>"s like global variables in
897 Perl - they have unlimited scope. This option also affects
898 "<TMPL_IF>" and "<TMPL_UNLESS>".
899
900 Example:
901
902 This is a normal variable: <TMPL_VAR NORMAL>.<P>
903
904 <TMPL_LOOP NAME=FROOT_LOOP>
905 Here it is inside the loop: <TMPL_VAR NORMAL><P>
906 </TMPL_LOOP>
907
908 Normally this wouldn't work as expected, since "<TMPL_VAR
909 NORMAL>"'s value outside the loop is not available inside the loop.
910
911 The global_vars option also allows you to access the values of an
912 enclosing loop within an inner loop. For example, in this loop the
913 inner loop will have access to the value of "OUTER_VAR" in the
914 correct iteration:
915
916 <TMPL_LOOP OUTER_LOOP>
917 OUTER: <TMPL_VAR OUTER_VAR>
918 <TMPL_LOOP INNER_LOOP>
919 INNER: <TMPL_VAR INNER_VAR>
920 INSIDE OUT: <TMPL_VAR OUTER_VAR>
921 </TMPL_LOOP>
922 </TMPL_LOOP>
923
924 One side-effect of "global_vars" is that variables you set with
925 param() that might otherwise be ignored when "die_on_bad_params" is
926 off will stick around. This is necessary to allow inner loops to
927 access values set for outer loops that don't directly use the
928 value.
929
930 NOTE: "global_vars" is not "global_loops" (which does not exist).
931 That means that loops you declare at one scope are not available
932 inside other loops even when "global_vars" is on.
933
934 • filter
935
936 This option allows you to specify a filter for your template files.
937 A filter is a subroutine that will be called after HTML::Template
938 reads your template file but before it starts parsing template
939 tags.
940
941 In the most simple usage, you simply assign a code reference to the
942 filter parameter. This subroutine will receive a single argument -
943 a reference to a string containing the template file text. Here is
944 an example that accepts templates with tags that look like
945 "!!!ZAP_VAR FOO!!!" and transforms them into HTML::Template tags:
946
947 my $filter = sub {
948 my $text_ref = shift;
949 $$text_ref =~ s/!!!ZAP_(.*?)!!!/<TMPL_$1>/g;
950 };
951
952 # open zap.tmpl using the above filter
953 my $template = HTML::Template->new(
954 filename => 'zap.tmpl',
955 filter => $filter,
956 );
957
958 More complicated usages are possible. You can request that your
959 filter receives the template text as an array of lines rather than
960 as a single scalar. To do that you need to specify your filter
961 using a hash-ref. In this form you specify the filter using the
962 "sub" key and the desired argument format using the "format" key.
963 The available formats are "scalar" and "array". Using the "array"
964 format will incur a performance penalty but may be more convenient
965 in some situations.
966
967 my $template = HTML::Template->new(
968 filename => 'zap.tmpl',
969 filter => {
970 sub => $filter,
971 format => 'array',
972 }
973 );
974
975 You may also have multiple filters. This allows simple filters to
976 be combined for more elaborate functionality. To do this you
977 specify an array of filters. The filters are applied in the order
978 they are specified.
979
980 my $template = HTML::Template->new(
981 filename => 'zap.tmpl',
982 filter => [
983 {
984 sub => \&decompress,
985 format => 'scalar',
986 },
987 {
988 sub => \&remove_spaces,
989 format => 'array',
990 },
991 ]
992 );
993
994 The specified filters will be called for any "TMPL_INCLUDE"ed files
995 just as they are for the main template file.
996
997 • default_escape
998
999 Set this parameter to a valid escape type (see the "escape" option)
1000 and HTML::Template will apply the specified escaping to all
1001 variables unless they declare a different escape in the template.
1002
1003 config
1004 A package method that is used to set/get the global default
1005 configuration options. For instance, if you want to set the "utf8"
1006 flag to always be on for every template loaded by this process you
1007 would do:
1008
1009 HTML::Template->config(utf8 => 1);
1010
1011 Or if you wanted to check if the "utf8" flag was on or not, you could
1012 do:
1013
1014 my %config = HTML::Template->config;
1015 if( $config{utf8} ) {
1016 ...
1017 }
1018
1019 Any configuration options that are valid for new() are acceptable to be
1020 passed to this method.
1021
1022 param
1023 param() can be called in a number of ways
1024
1025 1 - To return a list of parameters in the template :
1026 my @parameter_names = $self->param();
1027
1028 2 - To return the value set to a param :
1029 my $value = $self->param('PARAM');
1030
1031 3 - To set the value of a parameter :
1032 # For simple TMPL_VARs:
1033 $self->param(PARAM => 'value');
1034
1035 # with a subroutine reference that gets called to get the value
1036 # of the scalar. The sub will receive the template object as a
1037 # parameter.
1038 $self->param(PARAM => sub { return 'value' });
1039
1040 # And TMPL_LOOPs:
1041 $self->param(LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}]);
1042
1043 4 - To set the value of a number of parameters :
1044 # For simple TMPL_VARs:
1045 $self->param(
1046 PARAM => 'value',
1047 PARAM2 => 'value'
1048 );
1049
1050 # And with some TMPL_LOOPs:
1051 $self->param(
1052 PARAM => 'value',
1053 PARAM2 => 'value',
1054 LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1055 ANOTHER_LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1056 );
1057
1058 5 - To set the value of a number of parameters using a hash-ref :
1059 $self->param(
1060 {
1061 PARAM => 'value',
1062 PARAM2 => 'value',
1063 LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1064 ANOTHER_LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1065 }
1066 );
1067
1068 An error occurs if you try to set a value that is tainted if the
1069 "force_untaint" option is set.
1070
1071 clear_params
1072 Sets all the parameters to undef. Useful internally, if nowhere else!
1073
1074 output
1075 output() returns the final result of the template. In most situations
1076 you'll want to print this, like:
1077
1078 print $template->output();
1079
1080 When output is called each occurrence of "<TMPL_VAR NAME=name>" is
1081 replaced with the value assigned to "name" via param(). If a named
1082 parameter is unset it is simply replaced with ''. "<TMPL_LOOP>"s are
1083 evaluated once per parameter set, accumulating output on each pass.
1084
1085 Calling output() is guaranteed not to change the state of the
1086 HTML::Template object, in case you were wondering. This property is
1087 mostly important for the internal implementation of loops.
1088
1089 You may optionally supply a filehandle to print to automatically as the
1090 template is generated. This may improve performance and lower memory
1091 consumption. Example:
1092
1093 $template->output(print_to => *STDOUT);
1094
1095 The return value is undefined when using the "print_to" option.
1096
1097 query
1098 This method allow you to get information about the template structure.
1099 It can be called in a number of ways. The simplest usage of query is
1100 simply to check whether a parameter name exists in the template, using
1101 the "name" option:
1102
1103 if ($template->query(name => 'foo')) {
1104 # do something if a variable of any type named FOO is in the template
1105 }
1106
1107 This same usage returns the type of the parameter. The type is the
1108 same as the tag minus the leading 'TMPL_'. So, for example, a
1109 "TMPL_VAR" parameter returns 'VAR' from query().
1110
1111 if ($template->query(name => 'foo') eq 'VAR') {
1112 # do something if FOO exists and is a TMPL_VAR
1113 }
1114
1115 Note that the variables associated with "TMPL_IF"s and "TMPL_UNLESS"s
1116 will be identified as 'VAR' unless they are also used in a "TMPL_LOOP",
1117 in which case they will return 'LOOP'.
1118
1119 query() also allows you to get a list of parameters inside a loop (and
1120 inside loops inside loops). Example loop:
1121
1122 <TMPL_LOOP NAME="EXAMPLE_LOOP">
1123 <TMPL_VAR NAME="BEE">
1124 <TMPL_VAR NAME="BOP">
1125 <TMPL_LOOP NAME="EXAMPLE_INNER_LOOP">
1126 <TMPL_VAR NAME="INNER_BEE">
1127 <TMPL_VAR NAME="INNER_BOP">
1128 </TMPL_LOOP>
1129 </TMPL_LOOP>
1130
1131 And some query calls:
1132
1133 # returns 'LOOP'
1134 $type = $template->query(name => 'EXAMPLE_LOOP');
1135
1136 # returns ('bop', 'bee', 'example_inner_loop')
1137 @param_names = $template->query(loop => 'EXAMPLE_LOOP');
1138
1139 # both return 'VAR'
1140 $type = $template->query(name => ['EXAMPLE_LOOP', 'BEE']);
1141 $type = $template->query(name => ['EXAMPLE_LOOP', 'BOP']);
1142
1143 # and this one returns 'LOOP'
1144 $type = $template->query(name => ['EXAMPLE_LOOP', 'EXAMPLE_INNER_LOOP']);
1145
1146 # and finally, this returns ('inner_bee', 'inner_bop')
1147 @inner_param_names = $template->query(loop => ['EXAMPLE_LOOP', 'EXAMPLE_INNER_LOOP']);
1148
1149 # for non existent parameter names you get undef this returns undef.
1150 $type = $template->query(name => 'DWEAZLE_ZAPPA');
1151
1152 # calling loop on a non-loop parameter name will cause an error. This dies:
1153 $type = $template->query(loop => 'DWEAZLE_ZAPPA');
1154
1155 As you can see above the "loop" option returns a list of parameter
1156 names and both "name" and "loop" take array refs in order to refer to
1157 parameters inside loops. It is an error to use "loop" with a parameter
1158 that is not a loop.
1159
1160 Note that all the names are returned in lowercase and the types are
1161 uppercase.
1162
1163 Just like param(), query() with no arguments returns all the parameter
1164 names in the template at the top level.
1165
1167 As mentioned above, both "TMPL_VAR" and "TMPL_LOOP" values can be code
1168 references. These code references are only executed if the variable or
1169 loop is used in the template. This is extremely useful if you want to
1170 make a variable available to template designers but it can be expensive
1171 to calculate, so you only want to do so if you have to.
1172
1173 Maybe an example will help to illustrate. Let's say you have a template
1174 like this:
1175
1176 <tmpl_if we_care>
1177 <tmpl_if life_universe_and_everything>
1178 </tmpl_if>
1179
1180 If "life_universe_and_everything" is expensive to calculate we can wrap
1181 it's calculation in a code reference and HTML::Template will only
1182 execute that code if "we_care" is also true.
1183
1184 $tmpl->param(life_universe_and_everything => sub { calculate_42() });
1185
1186 Your code reference will be given a single argument, the HTML::Template
1187 object in use. In the above example, if we wanted calculate_42() to
1188 have this object we'd do something like this:
1189
1190 $tmpl->param(life_universe_and_everything => sub { calculate_42(shift) });
1191
1192 This same approach can be used for "TMPL_LOOP"s too:
1193
1194 <tmpl_if we_care>
1195 <tmpl_loop needles_in_haystack>
1196 Found <tmpl_var __counter>!
1197 </tmpl_loop>
1198 </tmpl_if>
1199
1200 And in your Perl code:
1201
1202 $tmpl->param(needles_in_haystack => sub { find_needles() });
1203
1204 The only difference in the "TMPL_LOOP" case is that the subroutine
1205 needs to return a reference to an ARRAY, not just a scalar value.
1206
1207 Multiple Calls
1208 It's important to recognize that while this feature is designed to save
1209 processing time when things aren't needed, if you're not careful it can
1210 actually increase the number of times you perform your calculation.
1211 HTML::Template calls your code reference each time it seems your loop
1212 in the template, this includes the times that you might use the loop in
1213 a conditional ("TMPL_IF" or "TMPL_UNLESS"). For instance:
1214
1215 <tmpl_if we care>
1216 <tmpl_if needles_in_haystack>
1217 <tmpl_loop needles_in_haystack>
1218 Found <tmpl_var __counter>!
1219 </tmpl_loop>
1220 <tmpl_else>
1221 No needles found!
1222 </tmpl_if>
1223 </tmpl_if>
1224
1225 This will actually call find_needles() twice which will be even worse
1226 than you had before. One way to work around this is to cache the
1227 return value yourself:
1228
1229 my $needles;
1230 $tmpl->param(needles_in_haystack => sub { defined $needles ? $needles : $needles = find_needles() });
1231
1233 I am aware of no bugs - if you find one, join the mailing list and tell
1234 us about it. You can join the HTML::Template mailing-list by visiting:
1235
1236 http://lists.sourceforge.net/lists/listinfo/html-template-users
1237
1238 Of course, you can still email me directly ("sam@tregar.com") with
1239 bugs, but I reserve the right to forward bug reports to the mailing
1240 list.
1241
1242 When submitting bug reports, be sure to include full details, including
1243 the VERSION of the module, a test script and a test template
1244 demonstrating the problem!
1245
1246 If you're feeling really adventurous, HTML::Template has a publically
1247 available Git repository. See below for more information in the PUBLIC
1248 GIT REPOSITORY section.
1249
1251 This module was the brain child of my boss, Jesse Erlbaum
1252 ("jesse@vm.com") at Vanguard Media (http://vm.com) . The most original
1253 idea in this module - the "<TMPL_LOOP>" - was entirely his.
1254
1255 Fixes, Bug Reports, Optimizations and Ideas have been generously
1256 provided by:
1257
1258 • Richard Chen
1259
1260 • Mike Blazer
1261
1262 • Adriano Nagelschmidt Rodrigues
1263
1264 • Andrej Mikus
1265
1266 • Ilya Obshadko
1267
1268 • Kevin Puetz
1269
1270 • Steve Reppucci
1271
1272 • Richard Dice
1273
1274 • Tom Hukins
1275
1276 • Eric Zylberstejn
1277
1278 • David Glasser
1279
1280 • Peter Marelas
1281
1282 • James William Carlson
1283
1284 • Frank D. Cringle
1285
1286 • Winfried Koenig
1287
1288 • Matthew Wickline
1289
1290 • Doug Steinwand
1291
1292 • Drew Taylor
1293
1294 • Tobias Brox
1295
1296 • Michael Lloyd
1297
1298 • Simran Gambhir
1299
1300 • Chris Houser <chouser@bluweb.com>
1301
1302 • Larry Moore
1303
1304 • Todd Larason
1305
1306 • Jody Biggs
1307
1308 • T.J. Mather
1309
1310 • Martin Schroth
1311
1312 • Dave Wolfe
1313
1314 • uchum
1315
1316 • Kawai Takanori
1317
1318 • Peter Guelich
1319
1320 • Chris Nokleberg
1321
1322 • Ralph Corderoy
1323
1324 • William Ward
1325
1326 • Ade Olonoh
1327
1328 • Mark Stosberg
1329
1330 • Lance Thomas
1331
1332 • Roland Giersig
1333
1334 • Jere Julian
1335
1336 • Peter Leonard
1337
1338 • Kenny Smith
1339
1340 • Sean P. Scanlon
1341
1342 • Martin Pfeffer
1343
1344 • David Ferrance
1345
1346 • Gyepi Sam
1347
1348 • Darren Chamberlain
1349
1350 • Paul Baker
1351
1352 • Gabor Szabo
1353
1354 • Craig Manley
1355
1356 • Richard Fein
1357
1358 • The Phalanx Project
1359
1360 • Sven Neuhaus
1361
1362 • Michael Peters
1363
1364 • Jan Dubois
1365
1366 • Moritz Lenz
1367
1368 Thanks!
1369
1371 You can find information about HTML::Template and other related modules
1372 at:
1373
1374 http://html-template.sourceforge.net
1375
1377 HTML::Template now has a publicly accessible Git repository provided by
1378 GitHub (github.com). You can access it by going to
1379 https://github.com/mpeters/html-template. Give it a try!
1380
1382 Sam Tregar, "sam@tregar.com"
1383
1385 Michael Peters, "mpeters@plusthree.com"
1386
1388 HTML::Template : A module for using HTML Templates with Perl
1389 Copyright (C) 2000-2011 Sam Tregar (sam@tregar.com)
1390
1391 This module is free software; you can redistribute it and/or modify it
1392 under the same terms as Perl itself, which means using either:
1393
1394 a) the GNU General Public License as published by the Free Software
1395 Foundation; either version 1, or (at your option) any later version,
1396
1397 or
1398
1399 b) the "Artistic License" which comes with this module.
1400
1401 This program is distributed in the hope that it will be useful,
1402 but WITHOUT ANY WARRANTY; without even the implied warranty of
1403 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either
1404 the GNU General Public License or the Artistic License for more details.
1405
1406 You should have received a copy of the Artistic License with this
1407 module. If not, I'll be glad to provide one.
1408
1409 You should have received a copy of the GNU General Public License
1410 along with this program. If not, write to the Free Software
1411 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
1412 USA
1413
1414
1415
1416perl v5.36.0 2023-01-20 HTML::Template(3)