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)
175 for this loop. The loop iterates over the list and produces output
176 from the text block for each pass. Unset parameters are skipped.
177 Here's an 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
248 an 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
468 information.
469
470 You can modify the Template object's behavior with "new()". The options
471 are available:
472
473 Error Detection Options
474
475 • die_on_bad_params
476
477 If set to 0 the module will let you call:
478
479 $template->param(param_name => 'value')
480
481 even if 'param_name' doesn't exist in the template body. Defaults
482 to 1.
483
484 • force_untaint
485
486 If set to 1 the module will not allow you to set unescaped
487 parameters with tainted values. If set to 2 you will have to
488 untaint all parameters, including ones with the escape attribute.
489 This option makes sure you untaint everything so you don't
490 accidentally introduce e.g. cross-site-scripting (XSS)
491 vulnerabilities. Requires taint mode. Defaults to 0.
492
493 • strict - if set to 0 the module will allow things that look like
494 they might be TMPL_* tags to get by without dieing. Example:
495
496 <TMPL_HUH NAME=ZUH>
497
498 Would normally cause an error, but if you call new with "strict =>
499 0" HTML::Template will ignore it. Defaults to 1.
500
501 • vanguard_compatibility_mode
502
503 If set to 1 the module will expect to see "<TMPL_VAR>"s that look
504 like "%NAME%" in addition to the standard syntax. Also sets
505 "die_on_bad_params =" 0>. If you're not at Vanguard Media trying
506 to use an old format template don't worry about this one. Defaults
507 to 0.
508
509 Caching Options
510
511 • cache
512
513 If set to 1 the module will cache in memory the parsed templates
514 based on the filename parameter, the modification date of the file
515 and the options passed to "new()". This only applies to templates
516 opened with the filename parameter specified, not scalarref or
517 arrayref templates. Caching also looks at the modification times
518 of any files included using "<TMPL_INCLUDE>" tags, but again, only
519 if the template is opened with filename parameter.
520
521 This is mainly of use in a persistent environment like
522 Apache/mod_perl. It has absolutely no benefit in a normal CGI
523 environment since the script is unloaded from memory after every
524 request. For a cache that does work for a non-persistent
525 environment see the "shared_cache" option below.
526
527 My simplistic testing shows that using cache yields a 90%
528 performance increase under mod_perl. Cache defaults to 0.
529
530 • shared_cache
531
532 If set to 1 the module will store its cache in shared memory using
533 the IPC::SharedCache module (available from CPAN). The effect of
534 this will be to maintain a single shared copy of each parsed
535 template for all instances of HTML::Template on the same machine to
536 use. This can be a significant reduction in memory usage in an
537 environment with a single machine but multiple servers. As an
538 example, on one of our systems we use 4MB of template cache and
539 maintain 25 httpd processes - shared_cache results in saving almost
540 100MB! Of course, some reduction in speed versus normal caching is
541 to be expected. Another difference between normal caching and
542 shared_cache is that shared_cache will work in a non-persistent
543 environment (like normal CGI) - normal caching is only useful in a
544 persistent environment like Apache/mod_perl.
545
546 By default HTML::Template uses the IPC key 'TMPL' as a shared root
547 segment (0x4c504d54 in hex), but this can be changed by setting the
548 "ipc_key" "new()" parameter to another 4-character or integer key.
549 Other options can be used to affect the shared memory cache
550 correspond to IPC::SharedCache options - "ipc_mode",
551 "ipc_segment_size" and "ipc_max_size". See IPC::SharedCache for a
552 description of how these work - in most cases you shouldn't need to
553 change them from the defaults.
554
555 For more information about the shared memory cache system used by
556 HTML::Template see IPC::SharedCache.
557
558 • double_cache
559
560 If set to 1 the module will use a combination of "shared_cache" and
561 normal cache mode for the best possible caching. Of course, it
562 also uses the most memory of all the cache modes. All the same
563 ipc_* options that work with "shared_cache" apply to "double_cache"
564 as well. Defaults to 0.
565
566 • blind_cache
567
568 If set to 1 the module behaves exactly as with normal caching but
569 does not check to see if the file has changed on each request.
570 This option should be used with caution, but could be of use on
571 high-load servers. My tests show "blind_cache" performing only 1
572 to 2 percent faster than cache under mod_perl.
573
574 NOTE: Combining this option with shared_cache can result in stale
575 templates stuck permanently in shared memory!
576
577 • file_cache
578
579 If set to 1 the module will store its cache in a file using the
580 Storable module. It uses no additional memory, and my simplistic
581 testing shows that it yields a 50% performance advantage. Like
582 "shared_cache", it will work in a non-persistent environments (like
583 CGI). Default is 0.
584
585 If you set this option you must set the "file_cache_dir" option.
586 See below for details.
587
588 NOTE: Storable uses "flock()" to ensure safe access to cache files.
589 Using "file_cache" on a system or filesystem (like NFS) without
590 "flock()" support is dangerous.
591
592 • file_cache_dir
593
594 Sets the directory where the module will store the cache files if
595 "file_cache" is enabled. Your script will need write permissions
596 to this directory. You'll also need to make sure the sufficient
597 space is available to store the cache files.
598
599 • file_cache_dir_mode
600
601 Sets the file mode for newly created "file_cache" directories and
602 subdirectories. Defaults to "0700" for security but this may be
603 inconvenient if you do not have access to the account running the
604 webserver.
605
606 • double_file_cache
607
608 If set to 1 the module will use a combination of "file_cache" and
609 normal "cache" mode for the best possible caching. The
610 file_cache_* options that work with file_cache apply to
611 "double_file_cache" as well. Defaults to 0.
612
613 • cache_lazy_vars
614
615 The option tells HTML::Template to cache the values returned from
616 code references used for "TMPL_VAR"s. See "LAZY VALUES" for
617 details.
618
619 • cache_lazy_loops
620
621 The option tells HTML::Template to cache the values returned from
622 code references used for "TMPL_LOOP"s. See "LAZY VALUES" for
623 details.
624
625 Filesystem Options
626
627 • path
628
629 You can set this variable with a list of paths to search for files
630 specified with the "filename" option to "new()" and for files
631 included with the "<TMPL_INCLUDE>" tag. This list is only
632 consulted when the filename is relative. The "HTML_TEMPLATE_ROOT"
633 environment variable is always tried first if it exists. Also, if
634 "HTML_TEMPLATE_ROOT" is set then an attempt will be made to prepend
635 "HTML_TEMPLATE_ROOT" onto paths in the path array. In the case of
636 a "<TMPL_INCLUDE>" file, the path to the including file is also
637 tried before path is consulted.
638
639 Example:
640
641 my $template = HTML::Template->new(
642 filename => 'file.tmpl',
643 path => ['/path/to/templates', '/alternate/path'],
644 );
645
646 NOTE: the paths in the path list must be expressed as UNIX paths,
647 separated by the forward-slash character ('/').
648
649 • search_path_on_include
650
651 If set to a true value the module will search from the top of the
652 array of paths specified by the path option on every
653 "<TMPL_INCLUDE>" and use the first matching template found. The
654 normal behavior is to look only in the current directory for a
655 template to include. Defaults to 0.
656
657 • utf8
658
659 Setting this to true tells HTML::Template to treat your template
660 files as UTF-8 encoded. This will apply to any file's passed to
661 "new()" or any included files. It won't do anything special to
662 scalars templates passed to "new()" since you should be doing the
663 encoding on those yourself.
664
665 my $template = HTML::Template->new(
666 filename => 'umlauts_are_awesome.tmpl',
667 utf8 => 1,
668 );
669
670 Most templates are either ASCII (the default) or UTF-8 encoded
671 Unicode. But if you need some other encoding other than these 2,
672 look at the "open_mode" option.
673
674 NOTE: The "utf8" and "open_mode" options cannot be used at the same
675 time.
676
677 • open_mode
678
679 You can set this option to an opening mode with which all template
680 files will be opened.
681
682 For example, if you want to use a template that is UTF-16 encoded
683 unicode:
684
685 my $template = HTML::Template->new(
686 filename => 'file.tmpl',
687 open_mode => '<:encoding(UTF-16)',
688 );
689
690 That way you can force a different encoding (than the default ASCII
691 or UTF-8), CR/LF properties etc. on the template files. See PerlIO
692 for details.
693
694 NOTE: this only works in perl 5.7.1 and above.
695
696 NOTE: you have to supply an opening mode that actually permits
697 reading from the file handle.
698
699 NOTE: The "utf8" and "open_mode" options cannot be used at the same
700 time.
701
702 Debugging Options
703
704 • debug
705
706 If set to 1 the module will write random debugging information to
707 STDERR. Defaults to 0.
708
709 • stack_debug
710
711 If set to 1 the module will use Data::Dumper to print out the
712 contents of the parse_stack to STDERR. Defaults to 0.
713
714 • cache_debug
715
716 If set to 1 the module will send information on cache loads, hits
717 and misses to STDERR. Defaults to 0.
718
719 • shared_cache_debug
720
721 If set to 1 the module will turn on the debug option in
722 IPC::SharedCache. Defaults to 0.
723
724 • memory_debug
725
726 If set to 1 the module will send information on cache memory usage
727 to STDERR. Requires the GTop module. Defaults to 0.
728
729 Miscellaneous Options
730
731 • associate
732
733 This option allows you to inherit the parameter values from other
734 objects. The only requirement for the other object is that it have
735 a "param()" method that works like HTML::Template's "param()". A
736 good candidate would be a CGI query object. Example:
737
738 my $query = CGI->new;
739 my $template = HTML::Template->new(
740 filename => 'template.tmpl',
741 associate => $query,
742 );
743
744 Now, "$template->output()" will act as though
745
746 $template->param(form_field => $cgi->param('form_field'));
747
748 had been specified for each key/value pair that would be provided
749 by the "$cgi->param()" method. Parameters you set directly take
750 precedence over associated parameters.
751
752 You can specify multiple objects to associate by passing an
753 anonymous array to the associate option. They are searched for
754 parameters in the order they appear:
755
756 my $template = HTML::Template->new(
757 filename => 'template.tmpl',
758 associate => [$query, $other_obj],
759 );
760
761 NOTE: The parameter names are matched in a case-insensitive manner.
762 If you have two parameters in a CGI object like 'NAME' and 'Name'
763 one will be chosen randomly by associate. This behavior can be
764 changed by the "case_sensitive" option.
765
766 • case_sensitive
767
768 Setting this option to true causes HTML::Template to treat template
769 variable names case-sensitively. The following example would only
770 set one parameter without the "case_sensitive" option:
771
772 my $template = HTML::Template->new(
773 filename => 'template.tmpl',
774 case_sensitive => 1
775 );
776 $template->param(
777 FieldA => 'foo',
778 fIELDa => 'bar',
779 );
780
781 This option defaults to off.
782
783 NOTE: with "case_sensitive" and "loop_context_vars" the special
784 loop variables are available in lower-case only.
785
786 • loop_context_vars
787
788 When this parameter is set to true (it is false by default) extra
789 variables that depend on the loop's context are made available
790 inside a loop. These are:
791
792 • __first__
793
794 Value that is true for the first iteration of the loop and
795 false every other time.
796
797 • __last__
798
799 Value that is true for the last iteration of the loop and false
800 every other time.
801
802 • __inner__
803
804 Value that is true for the every iteration of the loop except
805 for the first and last.
806
807 • __outer__
808
809 Value that is true for the first and last iterations of the
810 loop.
811
812 • __odd__
813
814 Value that is true for the every odd iteration of the loop.
815
816 • __even__
817
818 Value that is true for the every even iteration of the loop.
819
820 • __counter__
821
822 An integer (starting from 1) whose value increments for each
823 iteration of the loop.
824
825 • __index__
826
827 An integer (starting from 0) whose value increments for each
828 iteration of the loop.
829
830 Just like any other "TMPL_VAR"s these variables can be used in
831 "<TMPL_IF>", "<TMPL_UNLESS>" and "<TMPL_ELSE>" to control how a
832 loop is output.
833
834 Example:
835
836 <TMPL_LOOP NAME="FOO">
837 <TMPL_IF NAME="__first__">
838 This only outputs on the first pass.
839 </TMPL_IF>
840
841 <TMPL_IF NAME="__odd__">
842 This outputs every other pass, on the odd passes.
843 </TMPL_IF>
844
845 <TMPL_UNLESS NAME="__odd__">
846 This outputs every other pass, on the even passes.
847 </TMPL_UNLESS>
848
849 <TMPL_IF NAME="__inner__">
850 This outputs on passes that are neither first nor last.
851 </TMPL_IF>
852
853 This is pass number <TMPL_VAR NAME="__counter__">.
854
855 <TMPL_IF NAME="__last__">
856 This only outputs on the last pass.
857 </TMPL_IF>
858 </TMPL_LOOP>
859
860 One use of this feature is to provide a "separator" similar in
861 effect to the perl function "join()". Example:
862
863 <TMPL_LOOP FRUIT>
864 <TMPL_IF __last__> and </TMPL_IF>
865 <TMPL_VAR KIND><TMPL_UNLESS __last__>, <TMPL_ELSE>.</TMPL_UNLESS>
866 </TMPL_LOOP>
867
868 Would output something like:
869
870 Apples, Oranges, Brains, Toes, and Kiwi.
871
872 Given an appropriate "param()" call, of course. NOTE: A loop with
873 only a single pass will get both "__first__" and "__last__" set to
874 true, but not "__inner__".
875
876 • no_includes
877
878 Set this option to 1 to disallow the "<TMPL_INCLUDE>" tag in the
879 template file. This can be used to make opening untrusted
880 templates slightly less dangerous. Defaults to 0.
881
882 • max_includes
883
884 Set this variable to determine the maximum depth that includes can
885 reach. Set to 10 by default. Including files to a depth greater
886 than this value causes an error message to be displayed. Set to 0
887 to disable this protection.
888
889 • die_on_missing_include
890
891 If true, then HTML::Template will die if it can't find a file for a
892 "<TMPL_INCLUDE>". This defaults to true.
893
894 • global_vars
895
896 Normally variables declared outside a loop are not available inside
897 a loop. This option makes "<TMPL_VAR>"s like global variables in
898 Perl - they have unlimited scope. This option also affects
899 "<TMPL_IF>" and "<TMPL_UNLESS>".
900
901 Example:
902
903 This is a normal variable: <TMPL_VAR NORMAL>.<P>
904
905 <TMPL_LOOP NAME=FROOT_LOOP>
906 Here it is inside the loop: <TMPL_VAR NORMAL><P>
907 </TMPL_LOOP>
908
909 Normally this wouldn't work as expected, since "<TMPL_VAR
910 NORMAL>"'s value outside the loop is not available inside the loop.
911
912 The global_vars option also allows you to access the values of an
913 enclosing loop within an inner loop. For example, in this loop the
914 inner loop will have access to the value of "OUTER_VAR" in the
915 correct iteration:
916
917 <TMPL_LOOP OUTER_LOOP>
918 OUTER: <TMPL_VAR OUTER_VAR>
919 <TMPL_LOOP INNER_LOOP>
920 INNER: <TMPL_VAR INNER_VAR>
921 INSIDE OUT: <TMPL_VAR OUTER_VAR>
922 </TMPL_LOOP>
923 </TMPL_LOOP>
924
925 One side-effect of "global_vars" is that variables you set with
926 "param()" that might otherwise be ignored when "die_on_bad_params"
927 is off will stick around. This is necessary to allow inner loops
928 to access values set for outer loops that don't directly use the
929 value.
930
931 NOTE: "global_vars" is not "global_loops" (which does not exist).
932 That means that loops you declare at one scope are not available
933 inside other loops even when "global_vars" is on.
934
935 • filter
936
937 This option allows you to specify a filter for your template files.
938 A filter is a subroutine that will be called after HTML::Template
939 reads your template file but before it starts parsing template
940 tags.
941
942 In the most simple usage, you simply assign a code reference to the
943 filter parameter. This subroutine will receive a single argument -
944 a reference to a string containing the template file text. Here is
945 an example that accepts templates with tags that look like
946 "!!!ZAP_VAR FOO!!!" and transforms them into HTML::Template tags:
947
948 my $filter = sub {
949 my $text_ref = shift;
950 $$text_ref =~ s/!!!ZAP_(.*?)!!!/<TMPL_$1>/g;
951 };
952
953 # open zap.tmpl using the above filter
954 my $template = HTML::Template->new(
955 filename => 'zap.tmpl',
956 filter => $filter,
957 );
958
959 More complicated usages are possible. You can request that your
960 filter receives the template text as an array of lines rather than
961 as a single scalar. To do that you need to specify your filter
962 using a hash-ref. In this form you specify the filter using the
963 "sub" key and the desired argument format using the "format" key.
964 The available formats are "scalar" and "array". Using the "array"
965 format will incur a performance penalty but may be more convenient
966 in some situations.
967
968 my $template = HTML::Template->new(
969 filename => 'zap.tmpl',
970 filter => {
971 sub => $filter,
972 format => 'array',
973 }
974 );
975
976 You may also have multiple filters. This allows simple filters to
977 be combined for more elaborate functionality. To do this you
978 specify an array of filters. The filters are applied in the order
979 they are specified.
980
981 my $template = HTML::Template->new(
982 filename => 'zap.tmpl',
983 filter => [
984 {
985 sub => \&decompress,
986 format => 'scalar',
987 },
988 {
989 sub => \&remove_spaces,
990 format => 'array',
991 },
992 ]
993 );
994
995 The specified filters will be called for any "TMPL_INCLUDE"ed files
996 just as they are for the main template file.
997
998 • default_escape
999
1000 Set this parameter to a valid escape type (see the "escape" option)
1001 and HTML::Template will apply the specified escaping to all
1002 variables unless they declare a different escape in the template.
1003
1004 config
1005 A package method that is used to set/get the global default
1006 configuration options. For instance, if you want to set the "utf8"
1007 flag to always be on for every template loaded by this process you
1008 would do:
1009
1010 HTML::Template->config(utf8 => 1);
1011
1012 Or if you wanted to check if the "utf8" flag was on or not, you could
1013 do:
1014
1015 my %config = HTML::Template->config;
1016 if( $config{utf8} ) {
1017 ...
1018 }
1019
1020 Any configuration options that are valid for "new()" are acceptable to
1021 be passed to this method.
1022
1023 param
1024 "param()" can be called in a number of ways
1025
1026 1 - To return a list of parameters in the template :
1027 my @parameter_names = $self->param();
1028
1029 2 - To return the value set to a param :
1030 my $value = $self->param('PARAM');
1031
1032 3 - To set the value of a parameter :
1033 # For simple TMPL_VARs:
1034 $self->param(PARAM => 'value');
1035
1036 # with a subroutine reference that gets called to get the value
1037 # of the scalar. The sub will receive the template object as a
1038 # parameter.
1039 $self->param(PARAM => sub { return 'value' });
1040
1041 # And TMPL_LOOPs:
1042 $self->param(LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}]);
1043
1044 4 - To set the value of a number of parameters :
1045 # For simple TMPL_VARs:
1046 $self->param(
1047 PARAM => 'value',
1048 PARAM2 => 'value'
1049 );
1050
1051 # And with some TMPL_LOOPs:
1052 $self->param(
1053 PARAM => 'value',
1054 PARAM2 => 'value',
1055 LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1056 ANOTHER_LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1057 );
1058
1059 5 - To set the value of a number of parameters using a hash-ref :
1060 $self->param(
1061 {
1062 PARAM => 'value',
1063 PARAM2 => 'value',
1064 LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1065 ANOTHER_LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}],
1066 }
1067 );
1068
1069 An error occurs if you try to set a value that is tainted if the
1070 "force_untaint" option is set.
1071
1072 clear_params
1073 Sets all the parameters to undef. Useful internally, if nowhere else!
1074
1075 output
1076 "output()" returns the final result of the template. In most
1077 situations you'll want to print this, like:
1078
1079 print $template->output();
1080
1081 When output is called each occurrence of "<TMPL_VAR NAME=name>" is
1082 replaced with the value assigned to "name" via "param()". If a named
1083 parameter is unset it is simply replaced with ''. "<TMPL_LOOP>"s are
1084 evaluated once per parameter set, accumulating output on each pass.
1085
1086 Calling "output()" is guaranteed not to change the state of the
1087 HTML::Template object, in case you were wondering. This property is
1088 mostly important for the internal implementation of loops.
1089
1090 You may optionally supply a filehandle to print to automatically as the
1091 template is generated. This may improve performance and lower memory
1092 consumption. Example:
1093
1094 $template->output(print_to => *STDOUT);
1095
1096 The return value is undefined when using the "print_to" option.
1097
1098 query
1099 This method allow you to get information about the template structure.
1100 It can be called in a number of ways. The simplest usage of query is
1101 simply to check whether a parameter name exists in the template, using
1102 the "name" option:
1103
1104 if ($template->query(name => 'foo')) {
1105 # do something if a variable of any type named FOO is in the template
1106 }
1107
1108 This same usage returns the type of the parameter. The type is the
1109 same as the tag minus the leading 'TMPL_'. So, for example, a
1110 "TMPL_VAR" parameter returns 'VAR' from "query()".
1111
1112 if ($template->query(name => 'foo') eq 'VAR') {
1113 # do something if FOO exists and is a TMPL_VAR
1114 }
1115
1116 Note that the variables associated with "TMPL_IF"s and "TMPL_UNLESS"s
1117 will be identified as 'VAR' unless they are also used in a "TMPL_LOOP",
1118 in which case they will return 'LOOP'.
1119
1120 "query()" also allows you to get a list of parameters inside a loop
1121 (and inside loops inside loops). Example loop:
1122
1123 <TMPL_LOOP NAME="EXAMPLE_LOOP">
1124 <TMPL_VAR NAME="BEE">
1125 <TMPL_VAR NAME="BOP">
1126 <TMPL_LOOP NAME="EXAMPLE_INNER_LOOP">
1127 <TMPL_VAR NAME="INNER_BEE">
1128 <TMPL_VAR NAME="INNER_BOP">
1129 </TMPL_LOOP>
1130 </TMPL_LOOP>
1131
1132 And some query calls:
1133
1134 # returns 'LOOP'
1135 $type = $template->query(name => 'EXAMPLE_LOOP');
1136
1137 # returns ('bop', 'bee', 'example_inner_loop')
1138 @param_names = $template->query(loop => 'EXAMPLE_LOOP');
1139
1140 # both return 'VAR'
1141 $type = $template->query(name => ['EXAMPLE_LOOP', 'BEE']);
1142 $type = $template->query(name => ['EXAMPLE_LOOP', 'BOP']);
1143
1144 # and this one returns 'LOOP'
1145 $type = $template->query(name => ['EXAMPLE_LOOP', 'EXAMPLE_INNER_LOOP']);
1146
1147 # and finally, this returns ('inner_bee', 'inner_bop')
1148 @inner_param_names = $template->query(loop => ['EXAMPLE_LOOP', 'EXAMPLE_INNER_LOOP']);
1149
1150 # for non existent parameter names you get undef this returns undef.
1151 $type = $template->query(name => 'DWEAZLE_ZAPPA');
1152
1153 # calling loop on a non-loop parameter name will cause an error. This dies:
1154 $type = $template->query(loop => 'DWEAZLE_ZAPPA');
1155
1156 As you can see above the "loop" option returns a list of parameter
1157 names and both "name" and "loop" take array refs in order to refer to
1158 parameters inside loops. It is an error to use "loop" with a parameter
1159 that is not a loop.
1160
1161 Note that all the names are returned in lowercase and the types are
1162 uppercase.
1163
1164 Just like "param()", "query()" with no arguments returns all the
1165 parameter names in the template at the top level.
1166
1168 As mentioned above, both "TMPL_VAR" and "TMPL_LOOP" values can be code
1169 references. These code references are only executed if the variable or
1170 loop is used in the template. This is extremely useful if you want to
1171 make a variable available to template designers but it can be expensive
1172 to calculate, so you only want to do so if you have to.
1173
1174 Maybe an example will help to illustrate. Let's say you have a template
1175 like this:
1176
1177 <tmpl_if we_care>
1178 <tmpl_if life_universe_and_everything>
1179 </tmpl_if>
1180
1181 If "life_universe_and_everything" is expensive to calculate we can wrap
1182 it's calculation in a code reference and HTML::Template will only
1183 execute that code if "we_care" is also true.
1184
1185 $tmpl->param(life_universe_and_everything => sub { calculate_42() });
1186
1187 Your code reference will be given a single argument, the HTML::Template
1188 object in use. In the above example, if we wanted "calculate_42()" to
1189 have this object we'd do something like this:
1190
1191 $tmpl->param(life_universe_and_everything => sub { calculate_42(shift) });
1192
1193 This same approach can be used for "TMPL_LOOP"s too:
1194
1195 <tmpl_if we_care>
1196 <tmpl_loop needles_in_haystack>
1197 Found <tmpl_var __counter>!
1198 </tmpl_loop>
1199 </tmpl_if>
1200
1201 And in your Perl code:
1202
1203 $tmpl->param(needles_in_haystack => sub { find_needles() });
1204
1205 The only difference in the "TMPL_LOOP" case is that the subroutine
1206 needs to return a reference to an ARRAY, not just a scalar value.
1207
1208 Multiple Calls
1209 It's important to recognize that while this feature is designed to save
1210 processing time when things aren't needed, if you're not careful it can
1211 actually increase the number of times you perform your calculation.
1212 HTML::Template calls your code reference each time it seems your loop
1213 in the template, this includes the times that you might use the loop in
1214 a conditional ("TMPL_IF" or "TMPL_UNLESS"). For instance:
1215
1216 <tmpl_if we care>
1217 <tmpl_if needles_in_haystack>
1218 <tmpl_loop needles_in_haystack>
1219 Found <tmpl_var __counter>!
1220 </tmpl_loop>
1221 <tmpl_else>
1222 No needles found!
1223 </tmpl_if>
1224 </tmpl_if>
1225
1226 This will actually call "find_needles()" twice which will be even worse
1227 than you had before. One way to work around this is to cache the
1228 return value yourself:
1229
1230 my $needles;
1231 $tmpl->param(needles_in_haystack => sub { defined $needles ? $needles : $needles = find_needles() });
1232
1234 I am aware of no bugs - if you find one, join the mailing list and tell
1235 us about it. You can join the HTML::Template mailing-list by visiting:
1236
1237 http://lists.sourceforge.net/lists/listinfo/html-template-users
1238
1239 Of course, you can still email me directly ("sam@tregar.com") with
1240 bugs, but I reserve the right to forward bug reports to the mailing
1241 list.
1242
1243 When submitting bug reports, be sure to include full details, including
1244 the VERSION of the module, a test script and a test template
1245 demonstrating the problem!
1246
1247 If you're feeling really adventurous, HTML::Template has a publically
1248 available Git repository. See below for more information in the PUBLIC
1249 GIT REPOSITORY section.
1250
1252 This module was the brain child of my boss, Jesse Erlbaum
1253 ("jesse@vm.com") at Vanguard Media (http://vm.com) . The most original
1254 idea in this module - the "<TMPL_LOOP>" - was entirely his.
1255
1256 Fixes, Bug Reports, Optimizations and Ideas have been generously
1257 provided by:
1258
1259 • Richard Chen
1260
1261 • Mike Blazer
1262
1263 • Adriano Nagelschmidt Rodrigues
1264
1265 • Andrej Mikus
1266
1267 • Ilya Obshadko
1268
1269 • Kevin Puetz
1270
1271 • Steve Reppucci
1272
1273 • Richard Dice
1274
1275 • Tom Hukins
1276
1277 • Eric Zylberstejn
1278
1279 • David Glasser
1280
1281 • Peter Marelas
1282
1283 • James William Carlson
1284
1285 • Frank D. Cringle
1286
1287 • Winfried Koenig
1288
1289 • Matthew Wickline
1290
1291 • Doug Steinwand
1292
1293 • Drew Taylor
1294
1295 • Tobias Brox
1296
1297 • Michael Lloyd
1298
1299 • Simran Gambhir
1300
1301 • Chris Houser <chouser@bluweb.com>
1302
1303 • Larry Moore
1304
1305 • Todd Larason
1306
1307 • Jody Biggs
1308
1309 • T.J. Mather
1310
1311 • Martin Schroth
1312
1313 • Dave Wolfe
1314
1315 • uchum
1316
1317 • Kawai Takanori
1318
1319 • Peter Guelich
1320
1321 • Chris Nokleberg
1322
1323 • Ralph Corderoy
1324
1325 • William Ward
1326
1327 • Ade Olonoh
1328
1329 • Mark Stosberg
1330
1331 • Lance Thomas
1332
1333 • Roland Giersig
1334
1335 • Jere Julian
1336
1337 • Peter Leonard
1338
1339 • Kenny Smith
1340
1341 • Sean P. Scanlon
1342
1343 • Martin Pfeffer
1344
1345 • David Ferrance
1346
1347 • Gyepi Sam
1348
1349 • Darren Chamberlain
1350
1351 • Paul Baker
1352
1353 • Gabor Szabo
1354
1355 • Craig Manley
1356
1357 • Richard Fein
1358
1359 • The Phalanx Project
1360
1361 • Sven Neuhaus
1362
1363 • Michael Peters
1364
1365 • Jan Dubois
1366
1367 • Moritz Lenz
1368
1369 Thanks!
1370
1372 You can find information about HTML::Template and other related modules
1373 at:
1374
1375 http://html-template.sourceforge.net
1376
1378 HTML::Template now has a publicly accessible Git repository provided by
1379 GitHub (github.com). You can access it by going to
1380 https://github.com/mpeters/html-template. Give it a try!
1381
1383 Sam Tregar, "sam@tregar.com"
1384
1386 Michael Peters, "mpeters@plusthree.com"
1387
1389 HTML::Template : A module for using HTML Templates with Perl
1390 Copyright (C) 2000-2011 Sam Tregar (sam@tregar.com)
1391
1392 This module is free software; you can redistribute it and/or modify it
1393 under the same terms as Perl itself, which means using either:
1394
1395 a) the GNU General Public License as published by the Free Software
1396 Foundation; either version 1, or (at your option) any later version,
1397
1398 or
1399
1400 b) the "Artistic License" which comes with this module.
1401
1402 This program is distributed in the hope that it will be useful,
1403 but WITHOUT ANY WARRANTY; without even the implied warranty of
1404 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either
1405 the GNU General Public License or the Artistic License for more details.
1406
1407 You should have received a copy of the Artistic License with this
1408 module. If not, I'll be glad to provide one.
1409
1410 You should have received a copy of the GNU General Public License
1411 along with this program. If not, write to the Free Software
1412 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
1413 USA
1414
1415
1416
1417perl v5.34.0 2022-01-21 HTML::Template(3)