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

NAME

6       Text::Template - Expand template text with embedded Perl
7

VERSION

9       This file documents "Text::Template" version 1.45
10

SYNOPSIS

12        use Text::Template;
13
14        $template = Text::Template->new(TYPE => 'FILE',  SOURCE => 'filename.tmpl');
15        $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] );
16        $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh );
17        $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' );
18        $template = Text::Template->new(PREPEND => q{use strict;}, ...);
19
20        # Use a different template file syntax:
21        $template = Text::Template->new(DELIMITERS => [$open, $close], ...);
22
23        $recipient = 'King';
24        $text = $template->fill_in();  # Replaces `{$recipient}' with `King'
25        print $text;
26
27        $T::recipient = 'Josh';
28        $text = $template->fill_in(PACKAGE => T);
29
30        # Pass many variables explicitly
31        $hash = { recipient => 'Abed-Nego',
32                  friends => [ 'me', 'you' ],
33                  enemies => { loathsome => 'Bill Gates',
34                               fearsome => 'Larry Ellison' },
35                };
36        $text = $template->fill_in(HASH => $hash, ...);
37        # $recipient is Abed-Nego,
38        # @friends is ( 'me', 'you' ),
39        # %enemies is ( loathsome => ..., fearsome => ... )
40
41        # Call &callback in case of programming errors in template
42        $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...);
43
44        # Evaluate program fragments in Safe compartment with restricted permissions
45        $text = $template->fill_in(SAFE => $compartment, ...);
46
47        # Print result text instead of returning it
48        $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...);
49
50        # Parse template with different template file syntax:
51        $text = $template->fill_in(DELIMITERS => [$open, $close], ...);
52        # Note that this is *faster* than using the default delimiters
53
54        # Prepend specified perl code to each fragment before evaluating:
55        $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...);
56
57        use Text::Template 'fill_in_string';
58        $text = fill_in_string( <<EOM, PACKAGE => 'T', ...);
59        Dear {$recipient},
60        Pay me at once.
61               Love,
62                G.V.
63        EOM
64
65        use Text::Template 'fill_in_file';
66        $text = fill_in_file($filename, ...);
67
68        # All templates will always have `use strict vars' attached to all fragments
69        Text::Template->always_prepend(q{use strict 'vars';});
70

DESCRIPTION

72       This is a library for generating form letters, building HTML pages, or
73       filling in templates generally.  A `template' is a piece of text that
74       has little Perl programs embedded in it here and there.  When you `fill
75       in' a template, you evaluate the little programs and replace them with
76       their values.
77
78       You can store a template in a file outside your program.  People can
79       modify the template without modifying the program.  You can separate
80       the formatting details from the main code, and put the formatting parts
81       of the program into the template.  That prevents code bloat and encour‐
82       ages functional separation.
83
84       Example
85
86       Here's an example of a template, which we'll suppose is stored in the
87       file "formletter.tmpl":
88
89               Dear {$title} {$lastname},
90
91               It has come to our attention that you are delinquent in your
92               {$monthname[$last_paid_month]} payment.  Please remit
93               ${sprintf("%.2f", $amount)} immediately, or your patellae may
94               be needlessly endangered.
95
96                               Love,
97
98                               Mark "Vizopteryx" Dominus
99
100       The result of filling in this template is a string, which might look
101       something like this:
102
103               Dear Mr. Gates,
104
105               It has come to our attention that you are delinquent in your
106               February payment.  Please remit
107               $392.12 immediately, or your patellae may
108               be needlessly endangered.
109
110                               Love,
111
112                               Mark "Vizopteryx" Dominus
113
114       Here is a complete program that transforms the example template into
115       the example result, and prints it out:
116
117               use Text::Template;
118
119               my $template = Text::Template->new(SOURCE => 'formletter.tmpl')
120                 or die "Couldn't construct template: $Text::Template::ERROR";
121
122               my @monthname = qw(January February March April May June
123                                  July August September October November December);
124               my %vars = (title => 'Mr.',
125                           firstname => 'Bill',
126                           lastname => 'Gates',
127                           last_paid_month => 1,   # February
128                           amount => 392.12,
129                           monthname => \@monthname,
130                          );
131
132               my $result = $template->fill_in(HASH => \%vars);
133
134               if (defined $result) { print $result }
135               else { die "Couldn't fill in template: $Text::Template::ERROR" }
136
137       Philosophy
138
139       When people make a template module like this one, they almost always
140       start by inventing a special syntax for substitutions.  For example,
141       they build it so that a string like "%%VAR%%" is replaced with the
142       value of $VAR.  Then they realize the need extra formatting, so they
143       put in some special syntax for formatting.  Then they need a loop, so
144       they invent a loop syntax.  Pretty soon they have a new little template
145       language.
146
147       This approach has two problems: First, their little language is crip‐
148       pled. If you need to do something the author hasn't thought of, you
149       lose.  Second: Who wants to learn another language?  You already know
150       Perl, so why not use it?
151
152       "Text::Template" templates are programmed in Perl.  You embed Perl code
153       in your template, with "{" at the beginning and "}" at the end.  If you
154       want a variable interpolated, you write it the way you would in Perl.
155       If you need to make a loop, you can use any of the Perl loop construc‐
156       tions.  All the Perl built-in functions are available.
157

Details

159       Template Parsing
160
161       The "Text::Template" module scans the template source.  An open brace
162       "{" begins a program fragment, which continues until the matching close
163       brace "}".  When the template is filled in, the program fragments are
164       evaluated, and each one is replaced with the resulting value to yield
165       the text that is returned.
166
167       A backslash "\" in front of a brace (or another backslash that is in
168       front of a brace) escapes its special meaning.  The result of filling
169       out this template:
170
171               \{ The sum of 1 and 2 is {1+2}  \}
172
173       is
174
175               { The sum of 1 and 2 is 3  }
176
177       If you have an unmatched brace, "Text::Template" will return a failure
178       code and a warning about where the problem is.  Backslashes that do not
179       precede a brace are passed through unchanged.  If you have a template
180       like this:
181
182               { "String that ends in a newline.\n" }
183
184       The backslash inside the string is passed through to Perl unchanged, so
185       the "\n" really does turn into a newline.  See the note at the end for
186       details about the way backslashes work.  Backslash processing is not
187       done when you specify alternative delimiters with the "DELIMITERS"
188       option.  (See "Alternative Delimiters", below.)
189
190       Each program fragment should be a sequence of Perl statements, which
191       are evaluated the usual way.  The result of the last statement executed
192       will be evaluted in scalar context; the result of this statement is a
193       string, which is interpolated into the template in place of the program
194       fragment itself.
195
196       The fragments are evaluated in order, and side effects from earlier
197       fragments will persist into later fragments:
198
199               {$x = @things; ''}The Lord High Chamberlain has gotten {$x}
200               things for me this year.
201               { $diff = $x - 17;
202                 $more = 'more'
203                 if ($diff == 0) {
204                   $diff = 'no';
205                 } elsif ($diff < 0) {
206                   $more = 'fewer';
207                 }
208                 '';
209               }
210               That is {$diff} {$more} than he gave me last year.
211
212       The value of $x set in the first line will persist into the next frag‐
213       ment that begins on the third line, and the values of $diff and $more
214       set in the second fragment will persist and be interpolated into the
215       last line.  The output will look something like this:
216
217               The Lord High Chamberlain has gotten 42
218               things for me this year.
219
220               That is 25 more than he gave me last year.
221
222       That is all the syntax there is.
223
224       The $OUT variable
225
226       There is one special trick you can play in a template.  Here is the
227       motivation for it:  Suppose you are going to pass an array, @items,
228       into the template, and you want the template to generate a bulleted
229       list with a header, like this:
230
231               Here is a list of the things I have got for you since 1907:
232                 * Ivory
233                 * Apes
234                 * Peacocks
235                 * ...
236
237       One way to do it is with a template like this:
238
239               Here is a list of the things I have got for you since 1907:
240               { my $blist = '';
241                 foreach $i (@items) {
242                   $blist .= qq{  * $i\n};
243                 }
244                 $blist;
245               }
246
247       Here we construct the list in a variable called $blist, which we return
248       at the end.  This is a little cumbersome.  There is a shortcut.
249
250       Inside of templates, there is a special variable called $OUT.  Anything
251       you append to this variable will appear in the output of the template.
252       Also, if you use $OUT in a program fragment, the normal behavior, of
253       replacing the fragment with its return value, is disabled; instead the
254       fragment is replaced with the value of $OUT.  This means that you can
255       write the template above like this:
256
257               Here is a list of the things I have got for you since 1907:
258               { foreach $i (@items) {
259                   $OUT .= "  * $i\n";
260                 }
261               }
262
263       $OUT is reinitialized to the empty string at the start of each program
264       fragment.  It is private to "Text::Template", so you can't use a vari‐
265       able named $OUT in your template without invoking the special behavior.
266
267       General Remarks
268
269       All "Text::Template" functions return "undef" on failure, and set the
270       variable $Text::Template::ERROR to contain an explanation of what went
271       wrong.  For example, if you try to create a template from a file that
272       does not exist, $Text::Template::ERROR will contain something like:
273
274               Couldn't open file xyz.tmpl: No such file or directory
275
276       "new"
277
278               $template = new Text::Template ( TYPE => ..., SOURCE => ... );
279
280       This creates and returns a new template object.  "new" returns "undef"
281       and sets $Text::Template::ERROR if it can't create the template object.
282       "SOURCE" says where the template source code will come from.  "TYPE"
283       says what kind of object the source is.
284
285       The most common type of source is a file:
286
287               new Text::Template ( TYPE => 'FILE', SOURCE => $filename );
288
289       This reads the template from the specified file.  The filename is
290       opened with the Perl "open" command, so it can be a pipe or anything
291       else that makes sense with "open".
292
293       The "TYPE" can also be "STRING", in which case the "SOURCE" should be a
294       string:
295
296               new Text::Template ( TYPE => 'STRING',
297                                    SOURCE => "This is the actual template!" );
298
299       The "TYPE" can be "ARRAY", in which case the source should be a refer‐
300       ence to an array of strings.  The concatenation of these strings is the
301       template:
302
303               new Text::Template ( TYPE => 'ARRAY',
304                                    SOURCE => [ "This is ", "the actual",
305                                                " template!",
306                                              ]
307                                  );
308
309       The "TYPE" can be FILEHANDLE, in which case the source should be an
310       open filehandle (such as you got from the "FileHandle" or "IO::*" pack‐
311       ages, or a glob, or a reference to a glob).  In this case "Text::Tem‐
312       plate" will read the text from the filehandle up to end-of-file, and
313       that text is the template:
314
315               # Read template source code from STDIN:
316               new Text::Template ( TYPE => 'FILEHANDLE',
317                                    SOURCE => \*STDIN  );
318
319       If you omit the "TYPE" attribute, it's taken to be "FILE".  "SOURCE" is
320       required.  If you omit it, the program will abort.
321
322       The words "TYPE" and "SOURCE" can be spelled any of the following ways:
323
324               TYPE    SOURCE
325               Type    Source
326               type    source
327               -TYPE   -SOURCE
328               -Type   -Source
329               -type   -source
330
331       Pick a style you like and stick with it.
332
333       "DELIMITERS"
334           You may also add a "DELIMITERS" option.  If this option is present,
335           its value should be a reference to an array of two strings.  The
336           first string is the string that signals the beginning of each pro‐
337           gram fragment, and the second string is the string that signals the
338           end of each program fragment.  See "Alternative Delimiters", below.
339
340       "UNTAINT"
341           If your program is running in taint mode, you may have problems if
342           your templates are stored in files.  Data read from files is con‐
343           sidered 'untrustworthy', and taint mode will not allow you to eval‐
344           uate the Perl code in the file.  (It is afraid that a malicious
345           person might have tampered with the file.)
346
347           In some environments, however, local files are trustworthy.  You
348           can tell "Text::Template" that a certain file is trustworthy by
349           supplying "UNTAINT => 1" in the call to "new".  This will tell
350           "Text::Template" to disable taint checks on template code that has
351           come from a file, as long as the filename itself is considered
352           trustworthy.  It will also disable taint checks on template code
353           that comes from a filehandle.  When used with "TYPE => 'string'" or
354           "TYPE => 'array'", it has no effect.
355
356           See perlsec for more complete information about tainting.
357
358           Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph
359           Baehr for help with this feature.
360
361       "PREPEND"
362           This option is passed along to the "fill_in" call unless it is
363           overridden in the arguments to "fill_in".  See ""PREPEND" feature
364           and using "strict" in templates" below.
365
366       "BROKEN"
367           This option is passed along to the "fill_in" call unless it is
368           overridden in the arguments to "fill_in".  See "BROKEN" below.
369
370       "compile"
371
372               $template->compile()
373
374       Loads all the template text from the template's source, parses and com‐
375       piles it.  If successful, returns true; otherwise returns false and
376       sets $Text::Template::ERROR.  If the template is already compiled, it
377       returns true and does nothing.
378
379       You don't usually need to invoke this function, because "fill_in" (see
380       below) compiles the template if it isn't compiled already.
381
382       If there is an argument to this function, it must be a reference to an
383       array containing alternative delimiter strings.  See ""Alternative
384       Delimiters"", below.
385
386       "fill_in"
387
388               $template->fill_in(OPTIONS);
389
390       Fills in a template.  Returns the resulting text if successful.  Other‐
391       wise, returns "undef"  and sets $Text::Template::ERROR.
392
393       The OPTIONS are a hash, or a list of key-value pairs.  You can write
394       the key names in any of the six usual styles as above; this means that
395       where this manual says "PACKAGE" (for example) you can actually use any
396       of
397
398               PACKAGE Package package -PACKAGE -Package -package
399
400       Pick a style you like and stick with it.  The all-lowercase versions
401       may yield spurious warnings about
402
403               Ambiguous use of package => resolved to "package"
404
405       so you might like to avoid them and use the capitalized versions.
406
407       At present, there are eight legal options:  "PACKAGE", "BROKEN", "BRO‐
408       KEN_ARG", "SAFE", "HASH", "OUTPUT", and "DELIMITERS".
409
410       "PACKAGE"
411           "PACKAGE" specifies the name of a package in which the program
412           fragments should be evaluated.  The default is to use the package
413           from which "fill_in" was called.  For example, consider this tem‐
414           plate:
415
416                   The value of the variable x is {$x}.
417
418           If you use "$template->fill_in(PACKAGE => 'R')" , then the $x in
419           the template is actually replaced with the value of $R::x.  If you
420           omit the "PACKAGE" option, $x will be replaced with the value of
421           the $x variable in the package that actually called "fill_in".
422
423           You should almost always use "PACKAGE".  If you don't, and your
424           template makes changes to variables, those changes will be propa‐
425           gated back into the main program.  Evaluating the template in a
426           private package helps prevent this.  The template can still modify
427           variables in your program if it wants to, but it will have to do so
428           explicitly.  See the section at the end on `Security'.
429
430           Here's an example of using "PACKAGE":
431
432                   Your Royal Highness,
433
434                   Enclosed please find a list of things I have gotten
435                   for you since 1907:
436
437                   { foreach $item (@items) {
438                       $item_no++;
439                       $OUT .= " $item_no. \u$item\n";
440                     }
441                   }
442
443                   Signed,
444                   Lord High Chamberlain
445
446           We want to pass in an array which will be assigned to the array
447           @items.  Here's how to do that:
448
449                   @items = ('ivory', 'apes', 'peacocks', );
450                   $template->fill_in();
451
452           This is not very safe.  The reason this isn't as safe is that if
453           you had a variable named $item_no in scope in your program at the
454           point you called "fill_in", its value would be clobbered by the act
455           of filling out the template.  The problem is the same as if you had
456           written a subroutine that used those variables in the same way that
457           the template does.  ($OUT is special in templates and is always
458           safe.)
459
460           One solution to this is to make the $item_no variable private to
461           the template by declaring it with "my".  If the template does this,
462           you are safe.
463
464           But if you use the "PACKAGE" option, you will probably be safe even
465           if the template does not declare its variables with "my":
466
467                   @Q::items = ('ivory', 'apes', 'peacocks', );
468                   $template->fill_in(PACKAGE => 'Q');
469
470           In this case the template will clobber the variable $Q::item_no,
471           which is not related to the one your program was using.
472
473           Templates cannot affect variables in the main program that are
474           declared with "my", unless you give the template references to
475           those variables.
476
477       "HASH"
478           You may not want to put the template variables into a package.
479           Packages can be hard to manage:  You can't copy them, for example.
480           "HASH" provides an alternative.
481
482           The value for "HASH" should be a reference to a hash that maps
483           variable names to values.  For example,
484
485                   $template->fill_in(HASH => { recipient => "The King",
486                                                items => ['gold', 'frankincense', 'myrrh'],
487                                                object => \$self,
488                                              });
489
490           will fill out the template and use "The King" as the value of
491           $recipient and the list of items as the value of @items.  Note that
492           we pass an array reference, but inside the template it appears as
493           an array.  In general, anything other than a simple string or num‐
494           ber should be passed by reference.
495
496           We also want to pass an object, which is in $self; note that we
497           pass a reference to the object, "\$self" instead.  Since we've
498           passed a reference to a scalar, inside the template the object
499           appears as $object.
500
501           The full details of how it works are a little involved, so you
502           might want to skip to the next section.
503
504           Suppose the key in the hash is key and the value is value.
505
506           *   If the value is "undef", then any variables named $key, @key,
507               %key, etc., are undefined.
508
509           *   If the value is a string or a number, then $key is set to that
510               value in the template.
511
512           *   For anything else, you must pass a reference.
513
514               If the value is a reference to an array, then @key is set to
515               that array.  If the value is a reference to a hash, then %key
516               is set to that hash.  Similarly if value is any other kind of
517               reference.  This means that
518
519                       var => "foo"
520
521               and
522
523                       var => \"foo"
524
525               have almost exactly the same effect.  (The difference is that
526               in the former case, the value is copied, and in the latter case
527               it is aliased.)
528
529           *   In particular, if you want the template to get an object or any
530               kind, you must pass a reference to it:
531
532                       $template->fill_in(HASH => { database_handle => \$dbh, ... });
533
534               If you do this, the template will have a variable $data‐
535               base_handle which is the database handle object.  If you leave
536               out the "\", the template will have a hash %database_handle,
537               which exposes the internal structure of the database handle
538               object; you don't want that.
539
540           Normally, the way this works is by allocating a private package,
541           loading all the variables into the package, and then filling out
542           the template as if you had specified that package.  A new package
543           is allocated each time.  However, if you also use the "PACKAGE"
544           option, "Text::Template" loads the variables into the package you
545           specified, and they stay there after the call returns.  Subsequent
546           calls to "fill_in" that use the same package will pick up the val‐
547           ues you loaded in.
548
549           If the argument of "HASH" is a reference to an array instead of a
550           reference to a hash, then the array should contain a list of hashes
551           whose contents are loaded into the template package one after the
552           other.  You can use this feature if you want to combine several
553           sets of variables.  For example, one set of variables might be the
554           defaults for a fill-in form, and the second set might be the user
555           inputs, which override the defaults when they are present:
556
557                   $template->fill_in(HASH => [\%defaults, \%user_input]);
558
559           You can also use this to set two variables with the same name:
560
561                   $template->fill_in(HASH => [{ v => "The King" },
562                                               { v => [1,2,3] },
563                                              ]
564                                     );
565
566           This sets $v to "The King" and @v to "(1,2,3)".
567
568       "BROKEN"
569           If any of the program fragments fails to compile or aborts for any
570           reason, and you have set the "BROKEN" option to a function refer‐
571           ence, "Text::Template" will invoke the function.  This function is
572           called the "BROKEN" function.  The "BROKEN" function will tell
573           "Text::Template" what to do next.
574
575           If the "BROKEN" function returns "undef", "Text::Template" will
576           immediately abort processing the template and return the text that
577           it has accumulated so far.  If your function does this, it should
578           set a flag that you can examine after "fill_in" returns so that you
579           can tell whether there was a premature return or not.
580
581           If the "BROKEN" function returns any other value, that value will
582           be interpolated into the template as if that value had been the
583           return value of the program fragment to begin with.  For example,
584           if the "BROKEN" function returns an error string, the error string
585           will be interpolated into the output of the template in place of
586           the program fragment that cased the error.
587
588           If you don't specify a "BROKEN" function, "Text::Template" supplies
589           a default one that returns something like
590
591                   Program fragment delivered error ``Illegal division by 0 at
592                   template line 37''
593
594           (Note that the format of this message has changed slightly since
595           version 1.31.)  The return value of the "BROKEN" function is inter‐
596           polated into the template at the place the error occurred, so that
597           this template:
598
599                   (3+4)*5 = { 3+4)*5 }
600
601           yields this result:
602
603                   (3+4)*5 = Program fragment delivered error ``syntax error at template line 1''
604
605           If you specify a value for the "BROKEN" attribute, it should be a
606           reference to a function that "fill_in" can call instead of the
607           default function.
608
609           "fill_in" will pass a hash to the "broken" function.  The hash will
610           have at least these three members:
611
612           "text"
613               The source code of the program fragment that failed
614
615           "error"
616               The text of the error message ($@) generated by eval.
617
618               The text has been modified to omit the trailing newline and to
619               include the name of the template file (if there was one).  The
620               line number counts from the beginning of the template, not from
621               the beginning of the failed program fragment.
622
623           "lineno"
624               The line number of the template at which the program fragment
625               began.
626
627           There may also be an "arg" member.  See "BROKEN_ARG", below
628
629       "BROKEN_ARG"
630           If you supply the "BROKEN_ARG" option to "fill_in", the value of
631           the option is passed to the "BROKEN" function whenever it is
632           called.  The default "BROKEN" function ignores the "BROKEN_ARG",
633           but you can write a custom "BROKEN" function that uses the "BRO‐
634           KEN_ARG" to get more information about what went wrong.
635
636           The "BROKEN" function could also use the "BROKEN_ARG" as a refer‐
637           ence to store an error message or some other information that it
638           wants to communicate back to the caller.  For example:
639
640                   $error = '';
641
642                   sub my_broken {
643                      my %args = @_;
644                      my $err_ref = $args{arg};
645                      ...
646                      $$err_ref = "Some error message";
647                      return undef;
648                   }
649
650                   $template->fill_in(BROKEN => \&my_broken,
651                                      BROKEN_ARG => \$error,
652                                     );
653
654                   if ($error) {
655                     die "It didn't work: $error";
656                   }
657
658           If one of the program fragments in the template fails, it will call
659           the "BROKEN" function, "my_broken", and pass it the "BROKEN_ARG",
660           which is a reference to $error.  "my_broken" can store an error
661           message into $error this way.  Then the function that called
662           "fill_in" can see if "my_broken" has left an error message for it
663           to find, and proceed accordingly.
664
665       "SAFE"
666           If you give "fill_in" a "SAFE" option, its value should be a safe
667           compartment object from the "Safe" package.  All evaluation of pro‐
668           gram fragments will be performed in this compartment.  See Safe for
669           full details about such compartments and how to restrict the opera‐
670           tions that can be performed in them.
671
672           If you use the "PACKAGE" option with "SAFE", the package you spec‐
673           ify will be placed into the safe compartment and evaluation will
674           take place in that package as usual.
675
676           If not, "SAFE" operation is a little different from the default.
677           Usually, if you don't specify a package, evaluation of program
678           fragments occurs in the package from which the template was
679           invoked.  But in "SAFE" mode the evaluation occurs inside the safe
680           compartment and cannot affect the calling package.  Normally, if
681           you use "HASH" without "PACKAGE", the hash variables are imported
682           into a private, one-use-only package.  But if you use "HASH" and
683           "SAFE" together without "PACKAGE", the hash variables will just be
684           loaded into the root namespace of the "Safe" compartment.
685
686       "OUTPUT"
687           If your template is going to generate a lot of text that you are
688           just going to print out again anyway,  you can save memory by hav‐
689           ing "Text::Template" print out the text as it is generated instead
690           of making it into a big string and returning the string.  If you
691           supply the "OUTPUT" option to "fill_in", the value should be a
692           filehandle.  The generated text will be printed to this filehandle
693           as it is constructed.  For example:
694
695                   $template->fill_in(OUTPUT => \*STDOUT, ...);
696
697           fills in the $template as usual, but the results are immediately
698           printed to STDOUT.  This may result in the output appearing more
699           quickly than it would have otherwise.
700
701           If you use "OUTPUT", the return value from "fill_in" is still true
702           on success and false on failure, but the complete text is not
703           returned to the caller.
704
705       "PREPEND"
706           You can have some Perl code prepended automatically to the begin‐
707           ning of every program fragment.  See ""PREPEND" feature and using
708           "strict" in templates" below.
709
710       "DELIMITERS"
711           If this option is present, its value should be a reference to a
712           list of two strings.  The first string is the string that signals
713           the beginning of each program fragment, and the second string is
714           the string that signals the end of each program fragment.  See
715           "Alternative Delimiters", below.
716
717           If you specify "DELIMITERS" in the call to "fill_in", they override
718           any delimiters you set when you created the template object with
719           "new".
720

Convenience Functions

722       "fill_this_in"
723
724       The basic way to fill in a template is to create a template object and
725       then call "fill_in" on it.   This is useful if you want to fill in the
726       same template more than once.
727
728       In some programs, this can be cumbersome.  "fill_this_in" accepts a
729       string, which contains the template, and a list of options, which are
730       passed to "fill_in" as above.  It constructs the template object for
731       you, fills it in as specified, and returns the results.  It returns
732       "undef" and sets $Text::Template::ERROR if it couldn't generate any
733       results.
734
735       An example:
736
737               $Q::name = 'Donald';
738               $Q::amount = 141.61;
739               $Q::part = 'hyoid bone';
740
741               $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q);
742               Dear {$name},
743               You owe me \\${sprintf('%.2f', $amount)}.
744               Pay or I will break your {$part}.
745                       Love,
746                       Grand Vizopteryx of Irkutsk.
747               EOM
748
749       Notice how we included the template in-line in the program by using a
750       `here document' with the "<<" notation.
751
752       "fill_this_in" is a deprecated feature.  It is only here for backwards
753       compatibility, and may be removed in some far-future version in
754       "Text::Template".  You should use "fill_in_string" instead.  It is
755       described in the next section.
756
757       "fill_in_string"
758
759       It is stupid that "fill_this_in" is a class method.  It should have
760       been just an imported function, so that you could omit the "Text::Tem‐
761       plate->" in the example above.  But I made the mistake four years ago
762       and it is too late to change it.
763
764       "fill_in_string" is exactly like "fill_this_in" except that it is not a
765       method and you can omit the "Text::Template->" and just say
766
767               print fill_in_string(<<'EOM', ...);
768               Dear {$name},
769                 ...
770               EOM
771
772       To use "fill_in_string", you need to say
773
774               use Text::Template 'fill_in_string';
775
776       at the top of your program.   You should probably use "fill_in_string"
777       instead of "fill_this_in".
778
779       "fill_in_file"
780
781       If you import "fill_in_file", you can say
782
783               $text = fill_in_file(filename, ...);
784
785       The "..." are passed to "fill_in" as above.  The filename is the name
786       of the file that contains the template you want to fill in.  It returns
787       the result text. or "undef", as usual.
788
789       If you are going to fill in the same file more than once in the same
790       program you should use the longer "new" / "fill_in" sequence instead.
791       It will be a lot faster because it only has to read and parse the file
792       once.
793
794       Including files into templates
795
796       People always ask for this.  ``Why don't you have an include func‐
797       tion?'' they want to know.  The short answer is this is Perl, and Perl
798       already has an include function.  If you want it, you can just put
799
800               {qx{cat filename}}
801
802       into your template.  VoilA.
803
804       If you don't want to use "cat", you can write a little four-line func‐
805       tion that opens a file and dumps out its contents, and call it from the
806       template.  I wrote one for you.  In the template, you can say
807
808               {Text::Template::_load_text(filename)}
809
810       If that is too verbose, here is a trick.  Suppose the template package
811       that you are going to be mentioning in the "fill_in" call is package
812       "Q".  Then in the main program, write
813
814               *Q::include = \&Text::Template::_load_text;
815
816       This imports the "_load_text" function into package "Q" with the name
817       "include".  From then on, any template that you fill in with package
818       "Q" can say
819
820               {include(filename)}
821
822       to insert the text from the named file at that point.  If you are using
823       the "HASH" option instead, just put "include => \&Text::Tem‐
824       plate::_load_text" into the hash instead of importing it explicitly.
825
826       Suppose you don't want to insert a plain text file, but rather you want
827       to include one template within another?  Just use "fill_in_file" in the
828       template itself:
829
830               {Text::Template::fill_in_file(filename)}
831
832       You can do the same importing trick if this is too much to type.
833

Miscellaneous

835       "my" variables
836
837       People are frequently surprised when this doesn't work:
838
839               my $recipient = 'The King';
840               my $text = fill_in_file('formletter.tmpl');
841
842       The text "The King" doesn't get into the form letter.  Why not?
843       Because $recipient is a "my" variable, and the whole point of "my"
844       variables is that they're private and inaccessible except in the scope
845       in which they're declared.  The template is not part of that scope, so
846       the template can't see $recipient.
847
848       If that's not the behavior you want, don't use "my".  "my" means a pri‐
849       vate variable, and in this case you don't want the variable to be pri‐
850       vate.  Put the variables into package variables in some other package,
851       and use the "PACKAGE" option to "fill_in":
852
853               $Q::recipient = $recipient;
854               my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q');
855
856       or pass the names and values in a hash with the "HASH" option:
857
858               my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient });
859
860       Security Matters
861
862       All variables are evaluated in the package you specify with the "PACK‐
863       AGE" option of "fill_in".  if you use this option, and if your tem‐
864       plates don't do anything egregiously stupid, you won't have to worry
865       that evaluation of the little programs will creep out into the rest of
866       your program and wreck something.
867
868       Nevertheless, there's really no way (except with "Safe") to protect
869       against a template that says
870
871               { $Important::Secret::Security::Enable = 0;
872                 # Disable security checks in this program
873               }
874
875       or
876
877               { $/ = "ho ho ho";   # Sabotage future uses of <FH>.
878                 # $/ is always a global variable
879               }
880
881       or even
882
883               { system("rm -rf /") }
884
885       so don't go filling in templates unless you're sure you know what's in
886       them.  If you're worried, or you can't trust the person who wrote the
887       template, use the "SAFE" option.
888
889       A final warning: program fragments run a small risk of accidentally
890       clobbering local variables in the "fill_in" function itself.  These
891       variables all have names that begin with $fi_, so if you stay away from
892       those names you'll be safe.  (Of course, if you're a real wizard you
893       can tamper with them deliberately for exciting effects; this is actu‐
894       ally how $OUT works.)  I can fix this, but it will make the package
895       slower to do it, so I would prefer not to.  If you are worried about
896       this, send me mail and I will show you what to do about it.
897
898       Alternative Delimiters
899
900       Lorenzo Valdettaro pointed out that if you are using "Text::Template"
901       to generate TeX output, the choice of braces as the program fragment
902       delimiters makes you suffer suffer suffer.  Starting in version 1.20,
903       you can change the choice of delimiters to something other than curly
904       braces.
905
906       In either the "new()" call or the "fill_in()" call, you can specify an
907       alternative set of delimiters with the "DELIMITERS" option.  For exam‐
908       ple, if you would like code fragments to be delimited by "[@--" and
909       "--@]" instead of "{" and "}", use
910
911               ... DELIMITERS => [ '[@--', '--@]' ], ...
912
913       Note that these delimiters are literal strings, not regexes.  (I tried
914       for regexes, but it complicates the lexical analysis too much.)  Note
915       also that "DELIMITERS" disables the special meaning of the backslash,
916       so if you want to include the delimiters in the literal text of your
917       template file, you are out of luck---it is up to you to choose delim‐
918       iters that do not conflict with what you are doing.  The delimiter
919       strings may still appear inside of program fragments as long as they
920       nest properly.  This means that if for some reason you absolutely must
921       have a program fragment that mentions one of the delimiters, like this:
922
923               [@--
924                       print "Oh no, a delimiter: --@]\n"
925               --@]
926
927       you may be able to make it work by doing this instead:
928
929               [@--
930                       # Fake matching delimiter in a comment: [@--
931                       print "Oh no, a delimiter: --@]\n"
932               --@]
933
934       It may be safer to choose delimiters that begin with a newline charac‐
935       ter.
936
937       Because the parsing of templates is simplified by the absence of back‐
938       slash escapes, using alternative "DELIMITERS" may speed up the parsing
939       process by 20-25%.  This shows that my original choice of "{" and "}"
940       was very bad.
941
942       "PREPEND" feature and using "strict" in templates
943
944       Suppose you would like to use "strict" in your templates to detect
945       undeclared variables and the like.  But each code fragment is a sepa‐
946       rate lexical scope, so you have to turn on "strict" at the top of each
947       and every code fragment:
948
949               { use strict;
950                 use vars '$foo';
951                 $foo = 14;
952                 ...
953               }
954
955               ...
956
957               { # we forgot to put `use strict' here
958                 my $result = $boo + 12;    # $boo is misspelled and should be $foo
959                 # No error is raised on `$boo'
960               }
961
962       Because we didn't put "use strict" at the top of the second fragment,
963       it was only active in the first fragment, and we didn't get any
964       "strict" checking in the second fragment.  Then we mispelled $foo and
965       the error wasn't caught.
966
967       "Text::Template" version 1.22 and higher has a new feature to make this
968       easier.  You can specify that any text at all be automatically added to
969       the beginning of each program fragment.
970
971       When you make a call to "fill_in", you can specify a
972
973               PREPEND => 'some perl statements here'
974
975       option; the statements will be prepended to each program fragment for
976       that one call only.  Suppose that the "fill_in" call included a
977
978               PREPEND => 'use strict;'
979
980       option, and that the template looked like this:
981
982               { use vars '$foo';
983                 $foo = 14;
984                 ...
985               }
986
987               ...
988
989               { my $result = $boo + 12;    # $boo is misspelled and should be $foo
990                 ...
991               }
992
993       The code in the second fragment would fail, because $boo has not been
994       declared.  "use strict" was implied, even though you did not write it
995       explicitly, because the "PREPEND" option added it for you automati‐
996       cally.
997
998       There are two other ways to do this.  At the time you create the tem‐
999       plate object with "new", you can also supply a "PREPEND" option, in
1000       which case the statements will be prepended each time you fill in that
1001       template.  If the "fill_in" call has its own "PREPEND" option, this
1002       overrides the one specified at the time you created the template.
1003       Finally, you can make the class method call
1004
1005               Text::Template->always_prepend('perl statements');
1006
1007       If you do this, then call calls to "fill_in" for any template will
1008       attach the perl statements to the beginning of each program fragment,
1009       except where overridden by "PREPEND" options to "new" or "fill_in".
1010
1011       Prepending in Derived Classes
1012
1013       This section is technical, and you should skip it on the first few
1014       readings.
1015
1016       Normally there are three places that prepended text could come from.
1017       It could come from the "PREPEND" option in the "fill_in" call, from the
1018       "PREPEND" option in the "new" call that created the template object, or
1019       from the argument of the "always_prepend" call.  "Text::Template" looks
1020       for these three things in order and takes the first one that it finds.
1021
1022       In a subclass of "Text::Template", this last possibility is ambiguous.
1023       Suppose "S" is a subclass of "Text::Template".  Should
1024
1025               Text::Template->always_prepend(...);
1026
1027       affect objects in class "Derived"?  The answer is that you can have it
1028       either way.
1029
1030       The "always_prepend" value for "Text::Template" is normally stored in
1031       a hash variable named %GLOBAL_PREPEND under the key "Text::Template".
1032       When "Text::Template" looks to see what text to prepend, it first looks
1033       in the template object itself, and if not, it looks in
1034       $GLOBAL_PREPEND{class} where class is the class to which the template
1035       object belongs.  If it doesn't find any value, it looks in
1036       $GLOBAL_PREPEND{'Text::Template'}.  This means that objects in class
1037       "Derived" will be affected by
1038
1039               Text::Template->always_prepend(...);
1040
1041       unless there is also a call to
1042
1043               Derived->always_prepend(...);
1044
1045       So when you're designing your derived class, you can arrange to have
1046       your objects ignore "Text::Template::always_prepend" calls by simply
1047       putting "Derived->always_prepend('')" at the top of your module.
1048
1049       Of course, there is also a final escape hatch: Templates support a
1050       "prepend_text" that is used to look up the appropriate text to be
1051       prepended at "fill_in" time.  Your derived class can override this
1052       method to get an arbitrary effect.
1053
1054       JavaScript
1055
1056       Jennifer D. St Clair asks:
1057
1058               > Most of my pages contain JavaScript and Stylesheets.
1059               > How do I change the template identifier?
1060
1061       Jennifer is worried about the braces in the JavaScript being taken as
1062       the delimiters of the Perl program fragments.  Of course, disaster will
1063       ensue when perl tries to evaluate these as if they were Perl programs.
1064       The best choice is to find some unambiguous delimiter strings that you
1065       can use in your template instead of curly braces, and then use the
1066       "DELIMITERS" option.  However, if you can't do this for some reason,
1067       there are  two easy workarounds:
1068
1069       1. You can put "\" in front of "{", "}", or "\" to remove its special
1070       meaning.  So, for example, instead of
1071
1072                   if (br== "n3") {
1073                       // etc.
1074                   }
1075
1076       you can put
1077
1078                   if (br== "n3") \{
1079                       // etc.
1080                   \}
1081
1082       and it'll come out of the template engine the way you want.
1083
1084       But here is another method that is probably better.  To see how it
1085       works, first consider what happens if you put this into a template:
1086
1087                   { 'foo' }
1088
1089       Since it's in braces, it gets evaluated, and obviously, this is going
1090       to turn into
1091
1092                   foo
1093
1094       So now here's the trick: In Perl, "q{...}" is the same as '...'.  So if
1095       we wrote
1096
1097                   {q{foo}}
1098
1099       it would turn into
1100
1101                   foo
1102
1103       So for your JavaScript, just write
1104
1105                   {q{if (br== "n3") {
1106                        // etc.
1107                      }}
1108                   }
1109
1110       and it'll come out as
1111
1112                     if (br== "n3") {
1113                         // etc.
1114                     }
1115
1116       which is what you want.
1117
1118       Shut Up!
1119
1120       People sometimes try to put an initialization section at the top of
1121       their templates, like this:
1122
1123               { ...
1124                 $var = 17;
1125               }
1126
1127       Then they complain because there is a 17 at the top of the output that
1128       they didn't want to have there.
1129
1130       Remember that a program fragment is replaced with its own return value,
1131       and that in Perl the return value of a code block is the value of the
1132       last expression that was evaluated, which in this case is 17.  If it
1133       didn't do that, you wouldn't be able to write "{$recipient}" and have
1134       the recipient filled in.
1135
1136       To prevent the 17 from appearing in the output is very simple:
1137
1138               { ...
1139                 $var = 17;
1140                 '';
1141               }
1142
1143       Now the last expression evaluated yields the empty string, which is
1144       invisible.  If you don't like the way this looks, use
1145
1146               { ...
1147                 $var = 17;
1148                 ($SILENTLY);
1149               }
1150
1151       instead.  Presumably, $SILENTLY has no value, so nothing will be inter‐
1152       polated.  This is what is known as a `trick'.
1153
1154       Compatibility
1155
1156       Every effort has been made to make this module compatible with older
1157       versions.  The only known exceptions follow:
1158
1159       The output format of the default "BROKEN" subroutine has changed twice,
1160       most recently between versions 1.31 and 1.40.
1161
1162       Starting in version 1.10, the $OUT variable is arrogated for a special
1163       meaning.  If you had templates before version 1.10 that happened to use
1164       a variable named $OUT, you will have to change them to use some other
1165       variable or all sorts of strangeness will result.
1166
1167       Between versions 0.1b and 1.00 the behavior of the \ metacharacter
1168       changed.  In 0.1b, \\ was special everywhere, and the template proces‐
1169       sor always replaced it with a single backslash before passing the code
1170       to Perl for evaluation.  The rule now is more complicated but probably
1171       more convenient.  See the section on backslash processing, below, for a
1172       full discussion.
1173
1174       Backslash Processing
1175
1176       In "Text::Template" beta versions, the backslash was special whenever
1177       it appeared before a brace or another backslash.  That meant that while
1178       "{"\n"}" did indeed generate a newline, "{"\\"}" did not generate a
1179       backslash, because the code passed to Perl for evaluation was "\" which
1180       is a syntax error.  If you wanted a backslash, you would have had to
1181       write "{"\\\\"}".
1182
1183       In "Text::Template" versions 1.00 through 1.10, there was a bug: Back‐
1184       slash was special everywhere.  In these versions, "{"\n"}" generated
1185       the letter "n".
1186
1187       The bug has been corrected in version 1.11, but I did not go back to
1188       exactly the old rule, because I did not like the idea of having to
1189       write "{"\\\\"}" to get one backslash.  The rule is now more compli‐
1190       cated to remember, but probably easier to use.  The rule is now: Back‐
1191       slashes are always passed to Perl unchanged unless they occur as part
1192       of a sequence like "\\\\\\{" or "\\\\\\}".  In these contexts, they are
1193       special; "\\" is replaced with "\", and "\{" and "\}" signal a literal
1194       brace.
1195
1196       Examples:
1197
1198               \{ foo \}
1199
1200       is not evaluated, because the "\" before the braces signals that they
1201       should be taken literally.  The result in the output looks like this:
1202
1203               { foo }
1204
1205       This is a syntax error:
1206
1207               { "foo}" }
1208
1209       because "Text::Template" thinks that the code ends at the first "}",
1210       and then gets upset when it sees the second one.  To make this work
1211       correctly, use
1212
1213               { "foo\}" }
1214
1215       This passes "foo}" to Perl for evaluation.  Note there's no "\" in the
1216       evaluated code.  If you really want a "\" in the evaluated code, use
1217
1218               { "foo\\\}" }
1219
1220       This passes "foo\}" to Perl for evaluation.
1221
1222       Starting with "Text::Template" version 1.20, backslash processing is
1223       disabled if you use the "DELIMITERS" option to specify alternative
1224       delimiter strings.
1225
1226       A short note about $Text::Template::ERROR
1227
1228       In the past some people have fretted about `violating the package
1229       boundary' by examining a variable inside the "Text::Template" package.
1230       Don't feel this way.  $Text::Template::ERROR is part of the published,
1231       official interface to this package.  It is perfectly OK to inspect this
1232       variable.  The interface is not going to change.
1233
1234       If it really, really bothers you, you can import a function called
1235       "TTerror" that returns the current value of the $ERROR variable.  So
1236       you can say:
1237
1238               use Text::Template 'TTerror';
1239
1240               my $template = new Text::Template (SOURCE => $filename);
1241               unless ($template) {
1242                 my $err = TTerror;
1243                 die "Couldn't make template: $err; aborting";
1244               }
1245
1246       I don't see what benefit this has over just doing this:
1247
1248               use Text::Template;
1249
1250               my $template = new Text::Template (SOURCE => $filename)
1251                 or die "Couldn't make template: $Text::Template::ERROR; aborting";
1252
1253       But if it makes you happy to do it that way, go ahead.
1254
1255       Sticky Widgets in Template Files
1256
1257       The "CGI" module provides functions for `sticky widgets', which are
1258       form input controls that retain their values from one page to the next.
1259       Sometimes people want to know how to include these widgets into their
1260       template output.
1261
1262       It's totally straightforward.  Just call the "CGI" functions from
1263       inside the template:
1264
1265               { $q->checkbox_group(NAME => 'toppings',
1266                                    LINEBREAK => true,
1267                                    COLUMNS => 3,
1268                                    VALUES => \@toppings,
1269                                   );
1270               }
1271
1272       Automatic preprocessing of program fragments
1273
1274       It may be useful to preprocess the program fragments before they are
1275       evaluated.  See "Text::Template::Preprocess" for more details.
1276
1277       Author
1278
1279       Mark-Jason Dominus, Plover Systems
1280
1281       Please send questions and other remarks about this software to
1282       "mjd-perl-template+@plover.com"
1283
1284       You can join a very low-volume (<10 messages per year) mailing list for
1285       announcements about this package.  Send an empty note to "mjd-perl-tem‐
1286       plate-request@plover.com" to join.
1287
1288       For updates, visit "http://www.plover.com/~mjd/perl/Template/".
1289
1290       Support?
1291
1292       This software is version 1.45.  It may have bugs.  Suggestions and bug
1293       reports are always welcome.  Send them to "mjd-perl-tem‐
1294       plate+@plover.com".  (That is my address, not the address of the mail‐
1295       ing list.  The mailing list address is a secret.)
1296

LICENSE

1298           Text::Template version 1.45
1299           Copyright (C) 2008 Mark Jason Dominus
1300
1301           This program is free software; you can redistribute it and/or
1302           modify it under the terms of the GNU General Public License as
1303           published by the Free Software Foundation; either version 2 of the
1304           License, or (at your option) any later version.  You may also can
1305           redistribute it and/or modify it under the terms of the Perl
1306           Artistic License.
1307
1308           This program is distributed in the hope that it will be useful,
1309           but WITHOUT ANY WARRANTY; without even the implied warranty of
1310           MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1311           GNU General Public License for more details.
1312
1313           You should have received copies of the GNU General Public License
1314           along with this program; if not, write to the Free Software
1315           Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
1316

THANKS

1318       Many thanks to the following people for offering support, encourage‐
1319       ment, advice, bug reports, and all the other good stuff.
1320
1321       David H. Adler / Joel Appelbaum / Klaus Arnhold / Antonio Araga~o /
1322       Kevin Atteson / Chris.Brezil / Mike Brodhead / Tom Brown / Dr. Frank
1323       Bucolo / Tim Bunce / Juan E. Camacho / Itamar Almeida de Carvalho /
1324       Joseph Cheek / Gene Damon / San Deng / Bob Dougherty / Marek Grac / Dan
1325       Franklin / gary at dls.net / Todd A. Green / Donald L. Greer Jr. /
1326       Michelangelo Grigni / Zac Hansen / Tom Henry / Jarko Hietaniemi / Matt
1327       X. Hunter / Robert M. Ioffe / Daniel LaLiberte / Reuven M. Lerner /
1328       Trip Lilley / Yannis Livassof / Val Luck / Kevin Madsen / David Mar‐
1329       shall / James Mastros / Joel Meulenberg / Jason Moore / Sergey Myas‐
1330       nikov / Chris Nandor / Bek Oberin / Steve Palincsar / Ron Pero / Hans
1331       Persson / Sean Roehnelt / Jonathan Roy / Shabbir J. Safdar / Jennifer
1332       D. St Clair / Uwe Schneider / Randal L. Schwartz / Michael G Schwern /
1333       Yonat Sharon / Brian C. Shensky / Niklas Skoglund / Tom Snee / Fred
1334       Steinberg / Hans Stoop / Michael J. Suzio / Dennis Taylor / James H.
1335       Thompson / Shad Todd / Lieven Tomme / Lorenzo Valdettaro / Larry Virden
1336       / Andy Wardley / Archie Warnock / Chris Wesley / Matt Womer / Andrew G
1337       Wood / Daini Xie / Michaely Yeung
1338
1339       Special thanks to:
1340
1341       Jonathan Roy
1342         for telling me how to do the "Safe" support (I spent two years worry‐
1343         ing about it, and then Jonathan pointed out that it was trivial.)
1344
1345       Ranjit Bhatnagar
1346         for demanding less verbose fragments like they have in ASP, for help‐
1347         ing me figure out the Right Thing, and, especially, for talking me
1348         out of adding any new syntax.  These discussions resulted in the $OUT
1349         feature.
1350
1351       Bugs and Caveats
1352
1353       "my" variables in "fill_in" are still susceptible to being clobbered by
1354       template evaluation.  They all begin with "fi_", so avoid those names
1355       in your templates.
1356
1357       The line number information will be wrong if the template's lines are
1358       not terminated by "\n".  You should let me know if this is a problem.
1359       If you do, I will fix it.
1360
1361       The $OUT variable has a special meaning in templates, so you cannot use
1362       it as if it were a regular variable.
1363
1364       There are not quite enough tests in the test suite.
1365
1366
1367
1368perl v5.8.8                       2008-04-16                 Text::Template(3)
Impressum