1Text::Template(3) User Contributed Perl Documentation Text::Template(3)
2
3
4
6 Text::Template - Expand template text with embedded Perl
7
9 This file documents "Text::Template" version 1.45
10
12 use Text::Template;
13
14
15 $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'filename.tmpl');
16 $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] );
17 $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh );
18 $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' );
19 $template = Text::Template->new(PREPEND => q{use strict;}, ...);
20
21 # Use a different template file syntax:
22 $template = Text::Template->new(DELIMITERS => [$open, $close], ...);
23
24 $recipient = 'King';
25 $text = $template->fill_in(); # Replaces `{$recipient}' with `King'
26 print $text;
27
28 $T::recipient = 'Josh';
29 $text = $template->fill_in(PACKAGE => T);
30
31 # Pass many variables explicitly
32 $hash = { recipient => 'Abed-Nego',
33 friends => [ 'me', 'you' ],
34 enemies => { loathsome => 'Bill Gates',
35 fearsome => 'Larry Ellison' },
36 };
37 $text = $template->fill_in(HASH => $hash, ...);
38 # $recipient is Abed-Nego,
39 # @friends is ( 'me', 'you' ),
40 # %enemies is ( loathsome => ..., fearsome => ... )
41
42
43 # Call &callback in case of programming errors in template
44 $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...);
45
46 # Evaluate program fragments in Safe compartment with restricted permissions
47 $text = $template->fill_in(SAFE => $compartment, ...);
48
49 # Print result text instead of returning it
50 $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...);
51
52 # Parse template with different template file syntax:
53 $text = $template->fill_in(DELIMITERS => [$open, $close], ...);
54 # Note that this is *faster* than using the default delimiters
55
56 # Prepend specified perl code to each fragment before evaluating:
57 $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...);
58
59 use Text::Template 'fill_in_string';
60 $text = fill_in_string( <<EOM, PACKAGE => 'T', ...);
61 Dear {$recipient},
62 Pay me at once.
63 Love,
64 G.V.
65 EOM
66
67 use Text::Template 'fill_in_file';
68 $text = fill_in_file($filename, ...);
69
70 # All templates will always have `use strict vars' attached to all fragments
71 Text::Template->always_prepend(q{use strict 'vars';});
72
74 This is a library for generating form letters, building HTML pages, or
75 filling in templates generally. A `template' is a piece of text that
76 has little Perl programs embedded in it here and there. When you `fill
77 in' a template, you evaluate the little programs and replace them with
78 their values.
79
80 You can store a template in a file outside your program. People can
81 modify the template without modifying the program. You can separate
82 the formatting details from the main code, and put the formatting parts
83 of the program into the template. That prevents code bloat and
84 encourages functional separation.
85
86 Example
87 Here's an example of a template, which we'll suppose is stored in the
88 file "formletter.tmpl":
89
90 Dear {$title} {$lastname},
91
92 It has come to our attention that you are delinquent in your
93 {$monthname[$last_paid_month]} payment. Please remit
94 ${sprintf("%.2f", $amount)} immediately, or your patellae may
95 be needlessly endangered.
96
97 Love,
98
99 Mark "Vizopteryx" Dominus
100
101 The result of filling in this template is a string, which might look
102 something like this:
103
104 Dear Mr. Gates,
105
106 It has come to our attention that you are delinquent in your
107 February payment. Please remit
108 $392.12 immediately, or your patellae may
109 be needlessly endangered.
110
111
112 Love,
113
114 Mark "Vizopteryx" Dominus
115
116 Here is a complete program that transforms the example template into
117 the example result, and prints it out:
118
119 use Text::Template;
120
121 my $template = Text::Template->new(SOURCE => 'formletter.tmpl')
122 or die "Couldn't construct template: $Text::Template::ERROR";
123
124 my @monthname = qw(January February March April May June
125 July August September October November December);
126 my %vars = (title => 'Mr.',
127 firstname => 'Bill',
128 lastname => 'Gates',
129 last_paid_month => 1, # February
130 amount => 392.12,
131 monthname => \@monthname,
132 );
133
134 my $result = $template->fill_in(HASH => \%vars);
135
136 if (defined $result) { print $result }
137 else { die "Couldn't fill in template: $Text::Template::ERROR" }
138
139 Philosophy
140 When people make a template module like this one, they almost always
141 start by inventing a special syntax for substitutions. For example,
142 they build it so that a string like "%%VAR%%" is replaced with the
143 value of $VAR. Then they realize the need extra formatting, so they
144 put in some special syntax for formatting. Then they need a loop, so
145 they invent a loop syntax. Pretty soon they have a new little template
146 language.
147
148 This approach has two problems: First, their little language is
149 crippled. If you need to do something the author hasn't thought of, you
150 lose. Second: Who wants to learn another language? You already know
151 Perl, so why not use it?
152
153 "Text::Template" templates are programmed in Perl. You embed Perl code
154 in your template, with "{" at the beginning and "}" at the end. If you
155 want a variable interpolated, you write it the way you would in Perl.
156 If you need to make a loop, you can use any of the Perl loop
157 constructions. All the Perl built-in functions are available.
158
160 Template Parsing
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
213 fragment that begins on the third line, and the values of $diff and
214 $more set in the second fragment will persist and be interpolated into
215 the 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 There is one special trick you can play in a template. Here is the
226 motivation for it: Suppose you are going to pass an array, @items,
227 into the template, and you want the template to generate a bulleted
228 list with a header, like this:
229
230 Here is a list of the things I have got for you since 1907:
231 * Ivory
232 * Apes
233 * Peacocks
234 * ...
235
236 One way to do it is with a template like this:
237
238 Here is a list of the things I have got for you since 1907:
239 { my $blist = '';
240 foreach $i (@items) {
241 $blist .= qq{ * $i\n};
242 }
243 $blist;
244 }
245
246 Here we construct the list in a variable called $blist, which we return
247 at the end. This is a little cumbersome. There is a shortcut.
248
249 Inside of templates, there is a special variable called $OUT. Anything
250 you append to this variable will appear in the output of the template.
251 Also, if you use $OUT in a program fragment, the normal behavior, of
252 replacing the fragment with its return value, is disabled; instead the
253 fragment is replaced with the value of $OUT. This means that you can
254 write the template above like this:
255
256 Here is a list of the things I have got for you since 1907:
257 { foreach $i (@items) {
258 $OUT .= " * $i\n";
259 }
260 }
261
262 $OUT is reinitialized to the empty string at the start of each program
263 fragment. It is private to "Text::Template", so you can't use a
264 variable named $OUT in your template without invoking the special
265 behavior.
266
267 General Remarks
268 All "Text::Template" functions return "undef" on failure, and set the
269 variable $Text::Template::ERROR to contain an explanation of what went
270 wrong. For example, if you try to create a template from a file that
271 does not exist, $Text::Template::ERROR will contain something like:
272
273 Couldn't open file xyz.tmpl: No such file or directory
274
275 "new"
276 $template = new Text::Template ( TYPE => ..., SOURCE => ... );
277
278 This creates and returns a new template object. "new" returns "undef"
279 and sets $Text::Template::ERROR if it can't create the template object.
280 "SOURCE" says where the template source code will come from. "TYPE"
281 says what kind of object the source is.
282
283 The most common type of source is a file:
284
285 new Text::Template ( TYPE => 'FILE', SOURCE => $filename );
286
287 This reads the template from the specified file. The filename is
288 opened with the Perl "open" command, so it can be a pipe or anything
289 else that makes sense with "open".
290
291 The "TYPE" can also be "STRING", in which case the "SOURCE" should be a
292 string:
293
294 new Text::Template ( TYPE => 'STRING',
295 SOURCE => "This is the actual template!" );
296
297 The "TYPE" can be "ARRAY", in which case the source should be a
298 reference to an array of strings. The concatenation of these strings
299 is the template:
300
301 new Text::Template ( TYPE => 'ARRAY',
302 SOURCE => [ "This is ", "the actual",
303 " template!",
304 ]
305 );
306
307 The "TYPE" can be FILEHANDLE, in which case the source should be an
308 open filehandle (such as you got from the "FileHandle" or "IO::*"
309 packages, or a glob, or a reference to a glob). In this case
310 "Text::Template" will read the text from the filehandle up to end-of-
311 file, and that text is the template:
312
313 # Read template source code from STDIN:
314 new Text::Template ( TYPE => 'FILEHANDLE',
315 SOURCE => \*STDIN );
316
317 If you omit the "TYPE" attribute, it's taken to be "FILE". "SOURCE" is
318 required. If you omit it, the program will abort.
319
320 The words "TYPE" and "SOURCE" can be spelled any of the following ways:
321
322 TYPE SOURCE
323 Type Source
324 type source
325 -TYPE -SOURCE
326 -Type -Source
327 -type -source
328
329 Pick a style you like and stick with it.
330
331 "DELIMITERS"
332 You may also add a "DELIMITERS" option. If this option is present,
333 its value should be a reference to an array of two strings. The
334 first string is the string that signals the beginning of each
335 program fragment, and the second string is the string that signals
336 the end of each program fragment. See "Alternative Delimiters",
337 below.
338
339 "UNTAINT"
340 If your program is running in taint mode, you may have problems if
341 your templates are stored in files. Data read from files is
342 considered 'untrustworthy', and taint mode will not allow you to
343 evaluate the Perl code in the file. (It is afraid that a malicious
344 person might have tampered with the file.)
345
346 In some environments, however, local files are trustworthy. You
347 can tell "Text::Template" that a certain file is trustworthy by
348 supplying "UNTAINT => 1" in the call to "new". This will tell
349 "Text::Template" to disable taint checks on template code that has
350 come from a file, as long as the filename itself is considered
351 trustworthy. It will also disable taint checks on template code
352 that comes from a filehandle. When used with "TYPE => 'string'" or
353 "TYPE => 'array'", it has no effect.
354
355 See perlsec for more complete information about tainting.
356
357 Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph
358 Baehr for help with this feature.
359
360 "PREPEND"
361 This option is passed along to the "fill_in" call unless it is
362 overridden in the arguments to "fill_in". See ""PREPEND" feature
363 and using "strict" in templates" below.
364
365 "BROKEN"
366 This option is passed along to the "fill_in" call unless it is
367 overridden in the arguments to "fill_in". See "BROKEN" below.
368
369 "compile"
370 $template->compile()
371
372 Loads all the template text from the template's source, parses and
373 compiles it. If successful, returns true; otherwise returns false and
374 sets $Text::Template::ERROR. If the template is already compiled, it
375 returns true and does nothing.
376
377 You don't usually need to invoke this function, because "fill_in" (see
378 below) compiles the template if it isn't compiled already.
379
380 If there is an argument to this function, it must be a reference to an
381 array containing alternative delimiter strings. See "Alternative
382 Delimiters", below.
383
384 "fill_in"
385 $template->fill_in(OPTIONS);
386
387 Fills in a template. Returns the resulting text if successful.
388 Otherwise, returns "undef" and sets $Text::Template::ERROR.
389
390 The OPTIONS are a hash, or a list of key-value pairs. You can write
391 the key names in any of the six usual styles as above; this means that
392 where this manual says "PACKAGE" (for example) you can actually use any
393 of
394
395 PACKAGE Package package -PACKAGE -Package -package
396
397 Pick a style you like and stick with it. The all-lowercase versions
398 may yield spurious warnings about
399
400 Ambiguous use of package => resolved to "package"
401
402 so you might like to avoid them and use the capitalized versions.
403
404 At present, there are eight legal options: "PACKAGE", "BROKEN",
405 "BROKEN_ARG", "SAFE", "HASH", "OUTPUT", and "DELIMITERS".
406
407 "PACKAGE"
408 "PACKAGE" specifies the name of a package in which the program
409 fragments should be evaluated. The default is to use the package
410 from which "fill_in" was called. For example, consider this
411 template:
412
413 The value of the variable x is {$x}.
414
415 If you use "$template->fill_in(PACKAGE => 'R')" , then the $x in
416 the template is actually replaced with the value of $R::x. If you
417 omit the "PACKAGE" option, $x will be replaced with the value of
418 the $x variable in the package that actually called "fill_in".
419
420 You should almost always use "PACKAGE". If you don't, and your
421 template makes changes to variables, those changes will be
422 propagated back into the main program. Evaluating the template in
423 a private package helps prevent this. The template can still
424 modify variables in your program if it wants to, but it will have
425 to do so explicitly. See the section at the end on `Security'.
426
427 Here's an example of using "PACKAGE":
428
429 Your Royal Highness,
430
431 Enclosed please find a list of things I have gotten
432 for you since 1907:
433
434 { foreach $item (@items) {
435 $item_no++;
436 $OUT .= " $item_no. \u$item\n";
437 }
438 }
439
440 Signed,
441 Lord High Chamberlain
442
443 We want to pass in an array which will be assigned to the array
444 @items. Here's how to do that:
445
446 @items = ('ivory', 'apes', 'peacocks', );
447 $template->fill_in();
448
449 This is not very safe. The reason this isn't as safe is that if
450 you had a variable named $item_no in scope in your program at the
451 point you called "fill_in", its value would be clobbered by the act
452 of filling out the template. The problem is the same as if you had
453 written a subroutine that used those variables in the same way that
454 the template does. ($OUT is special in templates and is always
455 safe.)
456
457 One solution to this is to make the $item_no variable private to
458 the template by declaring it with "my". If the template does this,
459 you are safe.
460
461 But if you use the "PACKAGE" option, you will probably be safe even
462 if the template does not declare its variables with "my":
463
464 @Q::items = ('ivory', 'apes', 'peacocks', );
465 $template->fill_in(PACKAGE => 'Q');
466
467 In this case the template will clobber the variable $Q::item_no,
468 which is not related to the one your program was using.
469
470 Templates cannot affect variables in the main program that are
471 declared with "my", unless you give the template references to
472 those variables.
473
474 "HASH"
475 You may not want to put the template variables into a package.
476 Packages can be hard to manage: You can't copy them, for example.
477 "HASH" provides an alternative.
478
479 The value for "HASH" should be a reference to a hash that maps
480 variable names to values. For example,
481
482 $template->fill_in(HASH => { recipient => "The King",
483 items => ['gold', 'frankincense', 'myrrh'],
484 object => \$self,
485 });
486
487 will fill out the template and use "The King" as the value of
488 $recipient and the list of items as the value of @items. Note that
489 we pass an array reference, but inside the template it appears as
490 an array. In general, anything other than a simple string or
491 number should be passed by reference.
492
493 We also want to pass an object, which is in $self; note that we
494 pass a reference to the object, "\$self" instead. Since we've
495 passed a reference to a scalar, inside the template the object
496 appears as $object.
497
498 The full details of how it works are a little involved, so you
499 might want to skip to the next section.
500
501 Suppose the key in the hash is key and the value is value.
502
503 · If the value is "undef", then any variables named $key, @key,
504 %key, etc., are undefined.
505
506 · If the value is a string or a number, then $key is set to that
507 value in the template.
508
509 · For anything else, you must pass a reference.
510
511 If the value is a reference to an array, then @key is set to
512 that array. If the value is a reference to a hash, then %key
513 is set to that hash. Similarly if value is any other kind of
514 reference. This means that
515
516 var => "foo"
517
518 and
519
520 var => \"foo"
521
522 have almost exactly the same effect. (The difference is that
523 in the former case, the value is copied, and in the latter case
524 it is aliased.)
525
526 · In particular, if you want the template to get an object or any
527 kind, you must pass a reference to it:
528
529 $template->fill_in(HASH => { database_handle => \$dbh, ... });
530
531 If you do this, the template will have a variable
532 $database_handle which is the database handle object. If you
533 leave out the "\", the template will have a hash
534 %database_handle, which exposes the internal structure of the
535 database handle object; you don't want that.
536
537 Normally, the way this works is by allocating a private package,
538 loading all the variables into the package, and then filling out
539 the template as if you had specified that package. A new package
540 is allocated each time. However, if you also use the "PACKAGE"
541 option, "Text::Template" loads the variables into the package you
542 specified, and they stay there after the call returns. Subsequent
543 calls to "fill_in" that use the same package will pick up the
544 values you loaded in.
545
546 If the argument of "HASH" is a reference to an array instead of a
547 reference to a hash, then the array should contain a list of hashes
548 whose contents are loaded into the template package one after the
549 other. You can use this feature if you want to combine several
550 sets of variables. For example, one set of variables might be the
551 defaults for a fill-in form, and the second set might be the user
552 inputs, which override the defaults when they are present:
553
554 $template->fill_in(HASH => [\%defaults, \%user_input]);
555
556 You can also use this to set two variables with the same name:
557
558 $template->fill_in(HASH => [{ v => "The King" },
559 { v => [1,2,3] },
560 ]
561 );
562
563 This sets $v to "The King" and @v to "(1,2,3)".
564
565 "BROKEN"
566 If any of the program fragments fails to compile or aborts for any
567 reason, and you have set the "BROKEN" option to a function
568 reference, "Text::Template" will invoke the function. This
569 function is called the "BROKEN" function. The "BROKEN" function
570 will tell "Text::Template" what to do next.
571
572 If the "BROKEN" function returns "undef", "Text::Template" will
573 immediately abort processing the template and return the text that
574 it has accumulated so far. If your function does this, it should
575 set a flag that you can examine after "fill_in" returns so that you
576 can tell whether there was a premature return or not.
577
578 If the "BROKEN" function returns any other value, that value will
579 be interpolated into the template as if that value had been the
580 return value of the program fragment to begin with. For example,
581 if the "BROKEN" function returns an error string, the error string
582 will be interpolated into the output of the template in place of
583 the program fragment that cased the error.
584
585 If you don't specify a "BROKEN" function, "Text::Template" supplies
586 a default one that returns something like
587
588 Program fragment delivered error ``Illegal division by 0 at
589 template line 37''
590
591 (Note that the format of this message has changed slightly since
592 version 1.31.) The return value of the "BROKEN" function is
593 interpolated into the template at the place the error occurred, so
594 that this template:
595
596 (3+4)*5 = { 3+4)*5 }
597
598 yields this result:
599
600 (3+4)*5 = Program fragment delivered error ``syntax error at template line 1''
601
602 If you specify a value for the "BROKEN" attribute, it should be a
603 reference to a function that "fill_in" can call instead of the
604 default function.
605
606 "fill_in" will pass a hash to the "broken" function. The hash will
607 have at least these three members:
608
609 "text"
610 The source code of the program fragment that failed
611
612 "error"
613 The text of the error message ($@) generated by eval.
614
615 The text has been modified to omit the trailing newline and to
616 include the name of the template file (if there was one). The
617 line number counts from the beginning of the template, not from
618 the beginning of the failed program fragment.
619
620 "lineno"
621 The line number of the template at which the program fragment
622 began.
623
624 There may also be an "arg" member. See "BROKEN_ARG", below
625
626 "BROKEN_ARG"
627 If you supply the "BROKEN_ARG" option to "fill_in", the value of
628 the option is passed to the "BROKEN" function whenever it is
629 called. The default "BROKEN" function ignores the "BROKEN_ARG",
630 but you can write a custom "BROKEN" function that uses the
631 "BROKEN_ARG" to get more information about what went wrong.
632
633 The "BROKEN" function could also use the "BROKEN_ARG" as a
634 reference to store an error message or some other information that
635 it wants to communicate back to the caller. For example:
636
637 $error = '';
638
639 sub my_broken {
640 my %args = @_;
641 my $err_ref = $args{arg};
642 ...
643 $$err_ref = "Some error message";
644 return undef;
645 }
646
647 $template->fill_in(BROKEN => \&my_broken,
648 BROKEN_ARG => \$error,
649 );
650
651 if ($error) {
652 die "It didn't work: $error";
653 }
654
655 If one of the program fragments in the template fails, it will call
656 the "BROKEN" function, "my_broken", and pass it the "BROKEN_ARG",
657 which is a reference to $error. "my_broken" can store an error
658 message into $error this way. Then the function that called
659 "fill_in" can see if "my_broken" has left an error message for it
660 to find, and proceed accordingly.
661
662 "SAFE"
663 If you give "fill_in" a "SAFE" option, its value should be a safe
664 compartment object from the "Safe" package. All evaluation of
665 program fragments will be performed in this compartment. See Safe
666 for full details about such compartments and how to restrict the
667 operations that can be performed in them.
668
669 If you use the "PACKAGE" option with "SAFE", the package you
670 specify will be placed into the safe compartment and evaluation
671 will take place in that package as usual.
672
673 If not, "SAFE" operation is a little different from the default.
674 Usually, if you don't specify a package, evaluation of program
675 fragments occurs in the package from which the template was
676 invoked. But in "SAFE" mode the evaluation occurs inside the safe
677 compartment and cannot affect the calling package. Normally, if
678 you use "HASH" without "PACKAGE", the hash variables are imported
679 into a private, one-use-only package. But if you use "HASH" and
680 "SAFE" together without "PACKAGE", the hash variables will just be
681 loaded into the root namespace of the "Safe" compartment.
682
683 "OUTPUT"
684 If your template is going to generate a lot of text that you are
685 just going to print out again anyway, you can save memory by
686 having "Text::Template" print out the text as it is generated
687 instead of making it into a big string and returning the string.
688 If you supply the "OUTPUT" option to "fill_in", the value should be
689 a filehandle. The generated text will be printed to this
690 filehandle as it is constructed. For example:
691
692 $template->fill_in(OUTPUT => \*STDOUT, ...);
693
694 fills in the $template as usual, but the results are immediately
695 printed to STDOUT. This may result in the output appearing more
696 quickly than it would have otherwise.
697
698 If you use "OUTPUT", the return value from "fill_in" is still true
699 on success and false on failure, but the complete text is not
700 returned to the caller.
701
702 "PREPEND"
703 You can have some Perl code prepended automatically to the
704 beginning of every program fragment. See ""PREPEND" feature and
705 using "strict" in templates" below.
706
707 "DELIMITERS"
708 If this option is present, its value should be a reference to a
709 list of two strings. The first string is the string that signals
710 the beginning of each program fragment, and the second string is
711 the string that signals the end of each program fragment. See
712 "Alternative Delimiters", below.
713
714 If you specify "DELIMITERS" in the call to "fill_in", they override
715 any delimiters you set when you created the template object with
716 "new".
717
719 "fill_this_in"
720 The basic way to fill in a template is to create a template object and
721 then call "fill_in" on it. This is useful if you want to fill in the
722 same template more than once.
723
724 In some programs, this can be cumbersome. "fill_this_in" accepts a
725 string, which contains the template, and a list of options, which are
726 passed to "fill_in" as above. It constructs the template object for
727 you, fills it in as specified, and returns the results. It returns
728 "undef" and sets $Text::Template::ERROR if it couldn't generate any
729 results.
730
731 An example:
732
733 $Q::name = 'Donald';
734 $Q::amount = 141.61;
735 $Q::part = 'hyoid bone';
736
737 $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q);
738 Dear {$name},
739 You owe me \\${sprintf('%.2f', $amount)}.
740 Pay or I will break your {$part}.
741 Love,
742 Grand Vizopteryx of Irkutsk.
743 EOM
744
745 Notice how we included the template in-line in the program by using a
746 `here document' with the "<<" notation.
747
748 "fill_this_in" is a deprecated feature. It is only here for backwards
749 compatibility, and may be removed in some far-future version in
750 "Text::Template". You should use "fill_in_string" instead. It is
751 described in the next section.
752
753 "fill_in_string"
754 It is stupid that "fill_this_in" is a class method. It should have
755 been just an imported function, so that you could omit the
756 "Text::Template->" in the example above. But I made the mistake four
757 years ago and it is too late to change it.
758
759 "fill_in_string" is exactly like "fill_this_in" except that it is not a
760 method and you can omit the "Text::Template->" and just say
761
762 print fill_in_string(<<'EOM', ...);
763 Dear {$name},
764 ...
765 EOM
766
767 To use "fill_in_string", you need to say
768
769 use Text::Template 'fill_in_string';
770
771 at the top of your program. You should probably use "fill_in_string"
772 instead of "fill_this_in".
773
774 "fill_in_file"
775 If you import "fill_in_file", you can say
776
777 $text = fill_in_file(filename, ...);
778
779 The "..." are passed to "fill_in" as above. The filename is the name
780 of the file that contains the template you want to fill in. It returns
781 the result text. or "undef", as usual.
782
783 If you are going to fill in the same file more than once in the same
784 program you should use the longer "new" / "fill_in" sequence instead.
785 It will be a lot faster because it only has to read and parse the file
786 once.
787
788 Including files into templates
789 People always ask for this. ``Why don't you have an include
790 function?'' they want to know. The short answer is this is Perl, and
791 Perl already has an include function. If you want it, you can just put
792
793 {qx{cat filename}}
794
795 into your template. Voila.
796
797 If you don't want to use "cat", you can write a little four-line
798 function that opens a file and dumps out its contents, and call it from
799 the template. I wrote one for you. In the template, you can say
800
801 {Text::Template::_load_text(filename)}
802
803 If that is too verbose, here is a trick. Suppose the template package
804 that you are going to be mentioning in the "fill_in" call is package
805 "Q". Then in the main program, write
806
807 *Q::include = \&Text::Template::_load_text;
808
809 This imports the "_load_text" function into package "Q" with the name
810 "include". From then on, any template that you fill in with package
811 "Q" can say
812
813 {include(filename)}
814
815 to insert the text from the named file at that point. If you are using
816 the "HASH" option instead, just put "include =>
817 \&Text::Template::_load_text" into the hash instead of importing it
818 explicitly.
819
820 Suppose you don't want to insert a plain text file, but rather you want
821 to include one template within another? Just use "fill_in_file" in the
822 template itself:
823
824 {Text::Template::fill_in_file(filename)}
825
826 You can do the same importing trick if this is too much to type.
827
829 "my" variables
830 People are frequently surprised when this doesn't work:
831
832 my $recipient = 'The King';
833 my $text = fill_in_file('formletter.tmpl');
834
835 The text "The King" doesn't get into the form letter. Why not?
836 Because $recipient is a "my" variable, and the whole point of "my"
837 variables is that they're private and inaccessible except in the scope
838 in which they're declared. The template is not part of that scope, so
839 the template can't see $recipient.
840
841 If that's not the behavior you want, don't use "my". "my" means a
842 private variable, and in this case you don't want the variable to be
843 private. Put the variables into package variables in some other
844 package, and use the "PACKAGE" option to "fill_in":
845
846 $Q::recipient = $recipient;
847 my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q');
848
849 or pass the names and values in a hash with the "HASH" option:
850
851 my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient });
852
853 Security Matters
854 All variables are evaluated in the package you specify with the
855 "PACKAGE" option of "fill_in". if you use this option, and if your
856 templates don't do anything egregiously stupid, you won't have to worry
857 that evaluation of the little programs will creep out into the rest of
858 your program and wreck something.
859
860 Nevertheless, there's really no way (except with "Safe") to protect
861 against a template that says
862
863 { $Important::Secret::Security::Enable = 0;
864 # Disable security checks in this program
865 }
866
867 or
868
869 { $/ = "ho ho ho"; # Sabotage future uses of <FH>.
870 # $/ is always a global variable
871 }
872
873 or even
874
875 { system("rm -rf /") }
876
877 so don't go filling in templates unless you're sure you know what's in
878 them. If you're worried, or you can't trust the person who wrote the
879 template, use the "SAFE" option.
880
881 A final warning: program fragments run a small risk of accidentally
882 clobbering local variables in the "fill_in" function itself. These
883 variables all have names that begin with $fi_, so if you stay away from
884 those names you'll be safe. (Of course, if you're a real wizard you
885 can tamper with them deliberately for exciting effects; this is
886 actually how $OUT works.) I can fix this, but it will make the package
887 slower to do it, so I would prefer not to. If you are worried about
888 this, send me mail and I will show you what to do about it.
889
890 Alternative Delimiters
891 Lorenzo Valdettaro pointed out that if you are using "Text::Template"
892 to generate TeX output, the choice of braces as the program fragment
893 delimiters makes you suffer suffer suffer. Starting in version 1.20,
894 you can change the choice of delimiters to something other than curly
895 braces.
896
897 In either the "new()" call or the "fill_in()" call, you can specify an
898 alternative set of delimiters with the "DELIMITERS" option. For
899 example, if you would like code fragments to be delimited by "[@--" and
900 "--@]" instead of "{" and "}", use
901
902 ... DELIMITERS => [ '[@--', '--@]' ], ...
903
904 Note that these delimiters are literal strings, not regexes. (I tried
905 for regexes, but it complicates the lexical analysis too much.) Note
906 also that "DELIMITERS" disables the special meaning of the backslash,
907 so if you want to include the delimiters in the literal text of your
908 template file, you are out of luck---it is up to you to choose
909 delimiters that do not conflict with what you are doing. The delimiter
910 strings may still appear inside of program fragments as long as they
911 nest properly. This means that if for some reason you absolutely must
912 have a program fragment that mentions one of the delimiters, like this:
913
914 [@--
915 print "Oh no, a delimiter: --@]\n"
916 --@]
917
918 you may be able to make it work by doing this instead:
919
920 [@--
921 # Fake matching delimiter in a comment: [@--
922 print "Oh no, a delimiter: --@]\n"
923 --@]
924
925 It may be safer to choose delimiters that begin with a newline
926 character.
927
928 Because the parsing of templates is simplified by the absence of
929 backslash escapes, using alternative "DELIMITERS" may speed up the
930 parsing process by 20-25%. This shows that my original choice of "{"
931 and "}" was very bad.
932
933 "PREPEND" feature and using "strict" in templates
934 Suppose you would like to use "strict" in your templates to detect
935 undeclared variables and the like. But each code fragment is a
936 separate lexical scope, so you have to turn on "strict" at the top of
937 each and every code fragment:
938
939 { use strict;
940 use vars '$foo';
941 $foo = 14;
942 ...
943 }
944
945 ...
946
947 { # we forgot to put `use strict' here
948 my $result = $boo + 12; # $boo is misspelled and should be $foo
949 # No error is raised on `$boo'
950 }
951
952 Because we didn't put "use strict" at the top of the second fragment,
953 it was only active in the first fragment, and we didn't get any
954 "strict" checking in the second fragment. Then we mispelled $foo and
955 the error wasn't caught.
956
957 "Text::Template" version 1.22 and higher has a new feature to make this
958 easier. You can specify that any text at all be automatically added to
959 the beginning of each program fragment.
960
961 When you make a call to "fill_in", you can specify a
962
963 PREPEND => 'some perl statements here'
964
965 option; the statements will be prepended to each program fragment for
966 that one call only. Suppose that the "fill_in" call included a
967
968 PREPEND => 'use strict;'
969
970 option, and that the template looked like this:
971
972 { use vars '$foo';
973 $foo = 14;
974 ...
975 }
976
977 ...
978
979 { my $result = $boo + 12; # $boo is misspelled and should be $foo
980 ...
981 }
982
983 The code in the second fragment would fail, because $boo has not been
984 declared. "use strict" was implied, even though you did not write it
985 explicitly, because the "PREPEND" option added it for you
986 automatically.
987
988 There are two other ways to do this. At the time you create the
989 template object with "new", you can also supply a "PREPEND" option, in
990 which case the statements will be prepended each time you fill in that
991 template. If the "fill_in" call has its own "PREPEND" option, this
992 overrides the one specified at the time you created the template.
993 Finally, you can make the class method call
994
995 Text::Template->always_prepend('perl statements');
996
997 If you do this, then call calls to "fill_in" for any template will
998 attach the perl statements to the beginning of each program fragment,
999 except where overridden by "PREPEND" options to "new" or "fill_in".
1000
1001 Prepending in Derived Classes
1002 This section is technical, and you should skip it on the first few
1003 readings.
1004
1005 Normally there are three places that prepended text could come from.
1006 It could come from the "PREPEND" option in the "fill_in" call, from the
1007 "PREPEND" option in the "new" call that created the template object, or
1008 from the argument of the "always_prepend" call. "Text::Template" looks
1009 for these three things in order and takes the first one that it finds.
1010
1011 In a subclass of "Text::Template", this last possibility is ambiguous.
1012 Suppose "S" is a subclass of "Text::Template". Should
1013
1014 Text::Template->always_prepend(...);
1015
1016 affect objects in class "Derived"? The answer is that you can have it
1017 either way.
1018
1019 The "always_prepend" value for "Text::Template" is normally stored in
1020 a hash variable named %GLOBAL_PREPEND under the key "Text::Template".
1021 When "Text::Template" looks to see what text to prepend, it first looks
1022 in the template object itself, and if not, it looks in
1023 $GLOBAL_PREPEND{class} where class is the class to which the template
1024 object belongs. If it doesn't find any value, it looks in
1025 $GLOBAL_PREPEND{'Text::Template'}. This means that objects in class
1026 "Derived" will be affected by
1027
1028 Text::Template->always_prepend(...);
1029
1030 unless there is also a call to
1031
1032 Derived->always_prepend(...);
1033
1034 So when you're designing your derived class, you can arrange to have
1035 your objects ignore "Text::Template::always_prepend" calls by simply
1036 putting "Derived->always_prepend('')" at the top of your module.
1037
1038 Of course, there is also a final escape hatch: Templates support a
1039 "prepend_text" that is used to look up the appropriate text to be
1040 prepended at "fill_in" time. Your derived class can override this
1041 method to get an arbitrary effect.
1042
1043 JavaScript
1044 Jennifer D. St Clair asks:
1045
1046 > Most of my pages contain JavaScript and Stylesheets.
1047 > How do I change the template identifier?
1048
1049 Jennifer is worried about the braces in the JavaScript being taken as
1050 the delimiters of the Perl program fragments. Of course, disaster will
1051 ensue when perl tries to evaluate these as if they were Perl programs.
1052 The best choice is to find some unambiguous delimiter strings that you
1053 can use in your template instead of curly braces, and then use the
1054 "DELIMITERS" option. However, if you can't do this for some reason,
1055 there are two easy workarounds:
1056
1057 1. You can put "\" in front of "{", "}", or "\" to remove its special
1058 meaning. So, for example, instead of
1059
1060 if (br== "n3") {
1061 // etc.
1062 }
1063
1064 you can put
1065
1066 if (br== "n3") \{
1067 // etc.
1068 \}
1069
1070 and it'll come out of the template engine the way you want.
1071
1072 But here is another method that is probably better. To see how it
1073 works, first consider what happens if you put this into a template:
1074
1075 { 'foo' }
1076
1077 Since it's in braces, it gets evaluated, and obviously, this is going
1078 to turn into
1079
1080 foo
1081
1082 So now here's the trick: In Perl, "q{...}" is the same as '...'. So if
1083 we wrote
1084
1085 {q{foo}}
1086
1087 it would turn into
1088
1089 foo
1090
1091 So for your JavaScript, just write
1092
1093 {q{if (br== "n3") {
1094 // etc.
1095 }}
1096 }
1097
1098 and it'll come out as
1099
1100 if (br== "n3") {
1101 // etc.
1102 }
1103
1104 which is what you want.
1105
1106 Shut Up!
1107 People sometimes try to put an initialization section at the top of
1108 their templates, like this:
1109
1110 { ...
1111 $var = 17;
1112 }
1113
1114 Then they complain because there is a 17 at the top of the output that
1115 they didn't want to have there.
1116
1117 Remember that a program fragment is replaced with its own return value,
1118 and that in Perl the return value of a code block is the value of the
1119 last expression that was evaluated, which in this case is 17. If it
1120 didn't do that, you wouldn't be able to write "{$recipient}" and have
1121 the recipient filled in.
1122
1123 To prevent the 17 from appearing in the output is very simple:
1124
1125 { ...
1126 $var = 17;
1127 '';
1128 }
1129
1130 Now the last expression evaluated yields the empty string, which is
1131 invisible. If you don't like the way this looks, use
1132
1133 { ...
1134 $var = 17;
1135 ($SILENTLY);
1136 }
1137
1138 instead. Presumably, $SILENTLY has no value, so nothing will be
1139 interpolated. This is what is known as a `trick'.
1140
1141 Compatibility
1142 Every effort has been made to make this module compatible with older
1143 versions. The only known exceptions follow:
1144
1145 The output format of the default "BROKEN" subroutine has changed twice,
1146 most recently between versions 1.31 and 1.40.
1147
1148 Starting in version 1.10, the $OUT variable is arrogated for a special
1149 meaning. If you had templates before version 1.10 that happened to use
1150 a variable named $OUT, you will have to change them to use some other
1151 variable or all sorts of strangeness will result.
1152
1153 Between versions 0.1b and 1.00 the behavior of the \ metacharacter
1154 changed. In 0.1b, \\ was special everywhere, and the template
1155 processor always replaced it with a single backslash before passing the
1156 code to Perl for evaluation. The rule now is more complicated but
1157 probably more convenient. See the section on backslash processing,
1158 below, for a full discussion.
1159
1160 Backslash Processing
1161 In "Text::Template" beta versions, the backslash was special whenever
1162 it appeared before a brace or another backslash. That meant that while
1163 "{"\n"}" did indeed generate a newline, "{"\\"}" did not generate a
1164 backslash, because the code passed to Perl for evaluation was "\" which
1165 is a syntax error. If you wanted a backslash, you would have had to
1166 write "{"\\\\"}".
1167
1168 In "Text::Template" versions 1.00 through 1.10, there was a bug:
1169 Backslash was special everywhere. In these versions, "{"\n"}"
1170 generated the letter "n".
1171
1172 The bug has been corrected in version 1.11, but I did not go back to
1173 exactly the old rule, because I did not like the idea of having to
1174 write "{"\\\\"}" to get one backslash. The rule is now more
1175 complicated to remember, but probably easier to use. The rule is now:
1176 Backslashes are always passed to Perl unchanged unless they occur as
1177 part of a sequence like "\\\\\\{" or "\\\\\\}". In these contexts,
1178 they are special; "\\" is replaced with "\", and "\{" and "\}" signal a
1179 literal brace.
1180
1181 Examples:
1182
1183 \{ foo \}
1184
1185 is not evaluated, because the "\" before the braces signals that they
1186 should be taken literally. The result in the output looks like this:
1187
1188 { foo }
1189
1190 This is a syntax error:
1191
1192 { "foo}" }
1193
1194 because "Text::Template" thinks that the code ends at the first "}",
1195 and then gets upset when it sees the second one. To make this work
1196 correctly, use
1197
1198 { "foo\}" }
1199
1200 This passes "foo}" to Perl for evaluation. Note there's no "\" in the
1201 evaluated code. If you really want a "\" in the evaluated code, use
1202
1203 { "foo\\\}" }
1204
1205 This passes "foo\}" to Perl for evaluation.
1206
1207 Starting with "Text::Template" version 1.20, backslash processing is
1208 disabled if you use the "DELIMITERS" option to specify alternative
1209 delimiter strings.
1210
1211 A short note about $Text::Template::ERROR
1212 In the past some people have fretted about `violating the package
1213 boundary' by examining a variable inside the "Text::Template" package.
1214 Don't feel this way. $Text::Template::ERROR is part of the published,
1215 official interface to this package. It is perfectly OK to inspect this
1216 variable. The interface is not going to change.
1217
1218 If it really, really bothers you, you can import a function called
1219 "TTerror" that returns the current value of the $ERROR variable. So
1220 you can say:
1221
1222 use Text::Template 'TTerror';
1223
1224 my $template = new Text::Template (SOURCE => $filename);
1225 unless ($template) {
1226 my $err = TTerror;
1227 die "Couldn't make template: $err; aborting";
1228 }
1229
1230 I don't see what benefit this has over just doing this:
1231
1232 use Text::Template;
1233
1234 my $template = new Text::Template (SOURCE => $filename)
1235 or die "Couldn't make template: $Text::Template::ERROR; aborting";
1236
1237 But if it makes you happy to do it that way, go ahead.
1238
1239 Sticky Widgets in Template Files
1240 The "CGI" module provides functions for `sticky widgets', which are
1241 form input controls that retain their values from one page to the next.
1242 Sometimes people want to know how to include these widgets into their
1243 template output.
1244
1245 It's totally straightforward. Just call the "CGI" functions from
1246 inside the template:
1247
1248 { $q->checkbox_group(NAME => 'toppings',
1249 LINEBREAK => true,
1250 COLUMNS => 3,
1251 VALUES => \@toppings,
1252 );
1253 }
1254
1255 Automatic preprocessing of program fragments
1256 It may be useful to preprocess the program fragments before they are
1257 evaluated. See "Text::Template::Preprocess" for more details.
1258
1259 Author
1260 Mark-Jason Dominus, Plover Systems
1261
1262 Please send questions and other remarks about this software to
1263 "mjd-perl-template+@plover.com"
1264
1265 You can join a very low-volume (<10 messages per year) mailing list for
1266 announcements about this package. Send an empty note to
1267 "mjd-perl-template-request@plover.com" to join.
1268
1269 For updates, visit "http://www.plover.com/~mjd/perl/Template/".
1270
1271 Support?
1272 This software is version 1.45. It may have bugs. Suggestions and bug
1273 reports are always welcome. Send them to
1274 "mjd-perl-template+@plover.com". (That is my address, not the address
1275 of the mailing list. The mailing list address is a secret.)
1276
1278 Text::Template version 1.45
1279 Copyright (C) 2008 Mark Jason Dominus
1280
1281 This program is free software; you can redistribute it and/or
1282 modify it under the terms of the GNU General Public License as
1283 published by the Free Software Foundation; either version 2 of the
1284 License, or (at your option) any later version. You may also can
1285 redistribute it and/or modify it under the terms of the Perl
1286 Artistic License.
1287
1288 This program is distributed in the hope that it will be useful,
1289 but WITHOUT ANY WARRANTY; without even the implied warranty of
1290 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1291 GNU General Public License for more details.
1292
1293 You should have received copies of the GNU General Public License
1294 along with this program; if not, write to the Free Software
1295 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
1296
1298 Many thanks to the following people for offering support,
1299 encouragement, advice, bug reports, and all the other good stuff.
1300
1301 David H. Adler / Joel Appelbaum / Klaus Arnhold / Antonio Araga~o /
1302 Kevin Atteson / Chris.Brezil / Mike Brodhead / Tom Brown / Dr. Frank
1303 Bucolo / Tim Bunce / Juan E. Camacho / Itamar Almeida de Carvalho /
1304 Joseph Cheek / Gene Damon / San Deng / Bob Dougherty / Marek Grac / Dan
1305 Franklin / gary at dls.net / Todd A. Green / Donald L. Greer Jr. /
1306 Michelangelo Grigni / Zac Hansen / Tom Henry / Jarko Hietaniemi / Matt
1307 X. Hunter / Robert M. Ioffe / Daniel LaLiberte / Reuven M. Lerner /
1308 Trip Lilley / Yannis Livassof / Val Luck / Kevin Madsen / David
1309 Marshall / James Mastros / Joel Meulenberg / Jason Moore / Sergey
1310 Myasnikov / Chris Nandor / Bek Oberin / Steve Palincsar / Ron Pero /
1311 Hans Persson / Sean Roehnelt / Jonathan Roy / Shabbir J. Safdar /
1312 Jennifer D. St Clair / Uwe Schneider / Randal L. Schwartz / Michael G
1313 Schwern / Yonat Sharon / Brian C. Shensky / Niklas Skoglund / Tom Snee
1314 / Fred Steinberg / Hans Stoop / Michael J. Suzio / Dennis Taylor /
1315 James H. Thompson / Shad Todd / Lieven Tomme / Lorenzo Valdettaro /
1316 Larry Virden / Andy Wardley / Archie Warnock / Chris Wesley / Matt
1317 Womer / Andrew G Wood / Daini Xie / Michaely Yeung
1318
1319 Special thanks to:
1320
1321 Jonathan Roy
1322 for telling me how to do the "Safe" support (I spent two years
1323 worrying about it, and then Jonathan pointed out that it was
1324 trivial.)
1325
1326 Ranjit Bhatnagar
1327 for demanding less verbose fragments like they have in ASP, for
1328 helping me figure out the Right Thing, and, especially, for talking
1329 me out of adding any new syntax. These discussions resulted in the
1330 $OUT feature.
1331
1332 Bugs and Caveats
1333 "my" variables in "fill_in" are still susceptible to being clobbered by
1334 template evaluation. They all begin with "fi_", so avoid those names
1335 in your templates.
1336
1337 The line number information will be wrong if the template's lines are
1338 not terminated by "\n". You should let me know if this is a problem.
1339 If you do, I will fix it.
1340
1341 The $OUT variable has a special meaning in templates, so you cannot use
1342 it as if it were a regular variable.
1343
1344 There are not quite enough tests in the test suite.
1345
1346
1347
1348perl v5.12.0 2008-04-16 Text::Template(3)