1Text::Template(3) User Contributed Perl Documentation Text::Template(3)
2
3
4
6 Text::Template - Expand template text with embedded Perl
7
9 version 1.51
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 evaluated 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", "FILENAME", "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 "FILENAME"
663 If you give "fill_in" a "FILENAME" option, then this is the file
664 name that you loaded the template source from. This only affects
665 the error message that is given for template errors. If you loaded
666 the template from "foo.txt" for example, and pass "foo.txt" as the
667 "FILENAME" parameter, errors will look like "... at foo.txt line N"
668 rather than "... at template line N".
669
670 Note that this does NOT have anything to do with loading a template
671 from the given filename. See "fill_in_file()" for that.
672
673 For example:
674
675 my $template = Text::Template->new(
676 TYPE => 'string',
677 SOURCE => 'The value is {1/0}');
678
679 $template->fill_in(FILENAME => 'foo.txt') or die $Text::Template::ERROR;
680
681 will die with an error that contains
682
683 Illegal division by zero at at foo.txt line 1
684
685 "SAFE"
686 If you give "fill_in" a "SAFE" option, its value should be a safe
687 compartment object from the "Safe" package. All evaluation of
688 program fragments will be performed in this compartment. See Safe
689 for full details about such compartments and how to restrict the
690 operations that can be performed in them.
691
692 If you use the "PACKAGE" option with "SAFE", the package you
693 specify will be placed into the safe compartment and evaluation
694 will take place in that package as usual.
695
696 If not, "SAFE" operation is a little different from the default.
697 Usually, if you don't specify a package, evaluation of program
698 fragments occurs in the package from which the template was
699 invoked. But in "SAFE" mode the evaluation occurs inside the safe
700 compartment and cannot affect the calling package. Normally, if
701 you use "HASH" without "PACKAGE", the hash variables are imported
702 into a private, one-use-only package. But if you use "HASH" and
703 "SAFE" together without "PACKAGE", the hash variables will just be
704 loaded into the root namespace of the "Safe" compartment.
705
706 "OUTPUT"
707 If your template is going to generate a lot of text that you are
708 just going to print out again anyway, you can save memory by
709 having "Text::Template" print out the text as it is generated
710 instead of making it into a big string and returning the string.
711 If you supply the "OUTPUT" option to "fill_in", the value should be
712 a filehandle. The generated text will be printed to this
713 filehandle as it is constructed. For example:
714
715 $template->fill_in(OUTPUT => \*STDOUT, ...);
716
717 fills in the $template as usual, but the results are immediately
718 printed to STDOUT. This may result in the output appearing more
719 quickly than it would have otherwise.
720
721 If you use "OUTPUT", the return value from "fill_in" is still true
722 on success and false on failure, but the complete text is not
723 returned to the caller.
724
725 "PREPEND"
726 You can have some Perl code prepended automatically to the
727 beginning of every program fragment. See ""PREPEND" feature and
728 using "strict" in templates" below.
729
730 "DELIMITERS"
731 If this option is present, its value should be a reference to a
732 list of two strings. The first string is the string that signals
733 the beginning of each program fragment, and the second string is
734 the string that signals the end of each program fragment. See
735 "Alternative Delimiters", below.
736
737 If you specify "DELIMITERS" in the call to "fill_in", they override
738 any delimiters you set when you created the template object with
739 "new".
740
742 "fill_this_in"
743 The basic way to fill in a template is to create a template object and
744 then call "fill_in" on it. This is useful if you want to fill in the
745 same template more than once.
746
747 In some programs, this can be cumbersome. "fill_this_in" accepts a
748 string, which contains the template, and a list of options, which are
749 passed to "fill_in" as above. It constructs the template object for
750 you, fills it in as specified, and returns the results. It returns
751 "undef" and sets $Text::Template::ERROR if it couldn't generate any
752 results.
753
754 An example:
755
756 $Q::name = 'Donald';
757 $Q::amount = 141.61;
758 $Q::part = 'hyoid bone';
759
760 $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q);
761 Dear {$name},
762 You owe me \\${sprintf('%.2f', $amount)}.
763 Pay or I will break your {$part}.
764 Love,
765 Grand Vizopteryx of Irkutsk.
766 EOM
767
768 Notice how we included the template in-line in the program by using a
769 `here document' with the "<<" notation.
770
771 "fill_this_in" is a deprecated feature. It is only here for backwards
772 compatibility, and may be removed in some far-future version in
773 "Text::Template". You should use "fill_in_string" instead. It is
774 described in the next section.
775
776 "fill_in_string"
777 It is stupid that "fill_this_in" is a class method. It should have
778 been just an imported function, so that you could omit the
779 "Text::Template->" in the example above. But I made the mistake four
780 years ago and it is too late to change it.
781
782 "fill_in_string" is exactly like "fill_this_in" except that it is not a
783 method and you can omit the "Text::Template->" and just say
784
785 print fill_in_string(<<'EOM', ...);
786 Dear {$name},
787 ...
788 EOM
789
790 To use "fill_in_string", you need to say
791
792 use Text::Template 'fill_in_string';
793
794 at the top of your program. You should probably use "fill_in_string"
795 instead of "fill_this_in".
796
797 "fill_in_file"
798 If you import "fill_in_file", you can say
799
800 $text = fill_in_file(filename, ...);
801
802 The "..." are passed to "fill_in" as above. The filename is the name
803 of the file that contains the template you want to fill in. It returns
804 the result text. or "undef", as usual.
805
806 If you are going to fill in the same file more than once in the same
807 program you should use the longer "new" / "fill_in" sequence instead.
808 It will be a lot faster because it only has to read and parse the file
809 once.
810
811 Including files into templates
812 People always ask for this. ``Why don't you have an include
813 function?'' they want to know. The short answer is this is Perl, and
814 Perl already has an include function. If you want it, you can just put
815
816 {qx{cat filename}}
817
818 into your template. Voilà.
819
820 If you don't want to use "cat", you can write a little four-line
821 function that opens a file and dumps out its contents, and call it from
822 the template. I wrote one for you. In the template, you can say
823
824 {Text::Template::_load_text(filename)}
825
826 If that is too verbose, here is a trick. Suppose the template package
827 that you are going to be mentioning in the "fill_in" call is package
828 "Q". Then in the main program, write
829
830 *Q::include = \&Text::Template::_load_text;
831
832 This imports the "_load_text" function into package "Q" with the name
833 "include". From then on, any template that you fill in with package
834 "Q" can say
835
836 {include(filename)}
837
838 to insert the text from the named file at that point. If you are using
839 the "HASH" option instead, just put "include =>
840 \&Text::Template::_load_text" into the hash instead of importing it
841 explicitly.
842
843 Suppose you don't want to insert a plain text file, but rather you want
844 to include one template within another? Just use "fill_in_file" in the
845 template itself:
846
847 {Text::Template::fill_in_file(filename)}
848
849 You can do the same importing trick if this is too much to type.
850
852 "my" variables
853 People are frequently surprised when this doesn't work:
854
855 my $recipient = 'The King';
856 my $text = fill_in_file('formletter.tmpl');
857
858 The text "The King" doesn't get into the form letter. Why not?
859 Because $recipient is a "my" variable, and the whole point of "my"
860 variables is that they're private and inaccessible except in the scope
861 in which they're declared. The template is not part of that scope, so
862 the template can't see $recipient.
863
864 If that's not the behavior you want, don't use "my". "my" means a
865 private variable, and in this case you don't want the variable to be
866 private. Put the variables into package variables in some other
867 package, and use the "PACKAGE" option to "fill_in":
868
869 $Q::recipient = $recipient;
870 my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q');
871
872 or pass the names and values in a hash with the "HASH" option:
873
874 my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient });
875
876 Security Matters
877 All variables are evaluated in the package you specify with the
878 "PACKAGE" option of "fill_in". if you use this option, and if your
879 templates don't do anything egregiously stupid, you won't have to worry
880 that evaluation of the little programs will creep out into the rest of
881 your program and wreck something.
882
883 Nevertheless, there's really no way (except with "Safe") to protect
884 against a template that says
885
886 { $Important::Secret::Security::Enable = 0;
887 # Disable security checks in this program
888 }
889
890 or
891
892 { $/ = "ho ho ho"; # Sabotage future uses of <FH>.
893 # $/ is always a global variable
894 }
895
896 or even
897
898 { system("rm -rf /") }
899
900 so don't go filling in templates unless you're sure you know what's in
901 them. If you're worried, or you can't trust the person who wrote the
902 template, use the "SAFE" option.
903
904 A final warning: program fragments run a small risk of accidentally
905 clobbering local variables in the "fill_in" function itself. These
906 variables all have names that begin with $fi_, so if you stay away from
907 those names you'll be safe. (Of course, if you're a real wizard you
908 can tamper with them deliberately for exciting effects; this is
909 actually how $OUT works.) I can fix this, but it will make the package
910 slower to do it, so I would prefer not to. If you are worried about
911 this, send me mail and I will show you what to do about it.
912
913 Alternative Delimiters
914 Lorenzo Valdettaro pointed out that if you are using "Text::Template"
915 to generate TeX output, the choice of braces as the program fragment
916 delimiters makes you suffer suffer suffer. Starting in version 1.20,
917 you can change the choice of delimiters to something other than curly
918 braces.
919
920 In either the "new()" call or the "fill_in()" call, you can specify an
921 alternative set of delimiters with the "DELIMITERS" option. For
922 example, if you would like code fragments to be delimited by "[@--" and
923 "--@]" instead of "{" and "}", use
924
925 ... DELIMITERS => [ '[@--', '--@]' ], ...
926
927 Note that these delimiters are literal strings, not regexes. (I tried
928 for regexes, but it complicates the lexical analysis too much.) Note
929 also that "DELIMITERS" disables the special meaning of the backslash,
930 so if you want to include the delimiters in the literal text of your
931 template file, you are out of luck---it is up to you to choose
932 delimiters that do not conflict with what you are doing. The delimiter
933 strings may still appear inside of program fragments as long as they
934 nest properly. This means that if for some reason you absolutely must
935 have a program fragment that mentions one of the delimiters, like this:
936
937 [@--
938 print "Oh no, a delimiter: --@]\n"
939 --@]
940
941 you may be able to make it work by doing this instead:
942
943 [@--
944 # Fake matching delimiter in a comment: [@--
945 print "Oh no, a delimiter: --@]\n"
946 --@]
947
948 It may be safer to choose delimiters that begin with a newline
949 character.
950
951 Because the parsing of templates is simplified by the absence of
952 backslash escapes, using alternative "DELIMITERS" may speed up the
953 parsing process by 20-25%. This shows that my original choice of "{"
954 and "}" was very bad.
955
956 "PREPEND" feature and using "strict" in templates
957 Suppose you would like to use "strict" in your templates to detect
958 undeclared variables and the like. But each code fragment is a
959 separate lexical scope, so you have to turn on "strict" at the top of
960 each and every code fragment:
961
962 { use strict;
963 use vars '$foo';
964 $foo = 14;
965 ...
966 }
967
968 ...
969
970 { # we forgot to put `use strict' here
971 my $result = $boo + 12; # $boo is misspelled and should be $foo
972 # No error is raised on `$boo'
973 }
974
975 Because we didn't put "use strict" at the top of the second fragment,
976 it was only active in the first fragment, and we didn't get any
977 "strict" checking in the second fragment. Then we misspelled $foo and
978 the error wasn't caught.
979
980 "Text::Template" version 1.22 and higher has a new feature to make this
981 easier. You can specify that any text at all be automatically added to
982 the beginning of each program fragment.
983
984 When you make a call to "fill_in", you can specify a
985
986 PREPEND => 'some perl statements here'
987
988 option; the statements will be prepended to each program fragment for
989 that one call only. Suppose that the "fill_in" call included a
990
991 PREPEND => 'use strict;'
992
993 option, and that the template looked like this:
994
995 { use vars '$foo';
996 $foo = 14;
997 ...
998 }
999
1000 ...
1001
1002 { my $result = $boo + 12; # $boo is misspelled and should be $foo
1003 ...
1004 }
1005
1006 The code in the second fragment would fail, because $boo has not been
1007 declared. "use strict" was implied, even though you did not write it
1008 explicitly, because the "PREPEND" option added it for you
1009 automatically.
1010
1011 There are three other ways to do this. At the time you create the
1012 template object with "new", you can also supply a "PREPEND" option, in
1013 which case the statements will be prepended each time you fill in that
1014 template. If the "fill_in" call has its own "PREPEND" option, this
1015 overrides the one specified at the time you created the template.
1016 Finally, you can make the class method call
1017
1018 Text::Template->always_prepend('perl statements');
1019
1020 If you do this, then call calls to "fill_in" for any template will
1021 attach the perl statements to the beginning of each program fragment,
1022 except where overridden by "PREPEND" options to "new" or "fill_in".
1023
1024 An alternative to adding "use strict;" to the PREPEND option, you can
1025 pass STRICT => 1 to fill_in when also passing the HASH option.
1026
1027 Suppose that the "fill_in" call included both
1028
1029 HASH => {$foo => ''} and
1030 STRICT => 1
1031
1032 options, and that the template looked like this:
1033
1034 {
1035 $foo = 14;
1036 ...
1037 }
1038
1039 ...
1040
1041 { my $result = $boo + 12; # $boo is misspelled and should be $foo
1042 ...
1043 }
1044
1045 The code in the second fragment would fail, because $boo has not been
1046 declared. "use strict" was implied, even though you did not write it
1047 explicitly, because the "STRICT" option added it for you automatically.
1048 Any variable referenced in the template that is not in the "HASH"
1049 option will be an error.
1050
1051 Prepending in Derived Classes
1052 This section is technical, and you should skip it on the first few
1053 readings.
1054
1055 Normally there are three places that prepended text could come from.
1056 It could come from the "PREPEND" option in the "fill_in" call, from the
1057 "PREPEND" option in the "new" call that created the template object, or
1058 from the argument of the "always_prepend" call. "Text::Template" looks
1059 for these three things in order and takes the first one that it finds.
1060
1061 In a subclass of "Text::Template", this last possibility is ambiguous.
1062 Suppose "S" is a subclass of "Text::Template". Should
1063
1064 Text::Template->always_prepend(...);
1065
1066 affect objects in class "Derived"? The answer is that you can have it
1067 either way.
1068
1069 The "always_prepend" value for "Text::Template" is normally stored in
1070 a hash variable named %GLOBAL_PREPEND under the key "Text::Template".
1071 When "Text::Template" looks to see what text to prepend, it first looks
1072 in the template object itself, and if not, it looks in
1073 $GLOBAL_PREPEND{class} where class is the class to which the template
1074 object belongs. If it doesn't find any value, it looks in
1075 $GLOBAL_PREPEND{'Text::Template'}. This means that objects in class
1076 "Derived" will be affected by
1077
1078 Text::Template->always_prepend(...);
1079
1080 unless there is also a call to
1081
1082 Derived->always_prepend(...);
1083
1084 So when you're designing your derived class, you can arrange to have
1085 your objects ignore "Text::Template::always_prepend" calls by simply
1086 putting "Derived->always_prepend('')" at the top of your module.
1087
1088 Of course, there is also a final escape hatch: Templates support a
1089 "prepend_text" that is used to look up the appropriate text to be
1090 prepended at "fill_in" time. Your derived class can override this
1091 method to get an arbitrary effect.
1092
1093 JavaScript
1094 Jennifer D. St Clair asks:
1095
1096 > Most of my pages contain JavaScript and Stylesheets.
1097 > How do I change the template identifier?
1098
1099 Jennifer is worried about the braces in the JavaScript being taken as
1100 the delimiters of the Perl program fragments. Of course, disaster will
1101 ensue when perl tries to evaluate these as if they were Perl programs.
1102 The best choice is to find some unambiguous delimiter strings that you
1103 can use in your template instead of curly braces, and then use the
1104 "DELIMITERS" option. However, if you can't do this for some reason,
1105 there are two easy workarounds:
1106
1107 1. You can put "\" in front of "{", "}", or "\" to remove its special
1108 meaning. So, for example, instead of
1109
1110 if (br== "n3") {
1111 // etc.
1112 }
1113
1114 you can put
1115
1116 if (br== "n3") \{
1117 // etc.
1118 \}
1119
1120 and it'll come out of the template engine the way you want.
1121
1122 But here is another method that is probably better. To see how it
1123 works, first consider what happens if you put this into a template:
1124
1125 { 'foo' }
1126
1127 Since it's in braces, it gets evaluated, and obviously, this is going
1128 to turn into
1129
1130 foo
1131
1132 So now here's the trick: In Perl, "q{...}" is the same as '...'. So if
1133 we wrote
1134
1135 {q{foo}}
1136
1137 it would turn into
1138
1139 foo
1140
1141 So for your JavaScript, just write
1142
1143 {q{if (br== "n3") {
1144 // etc.
1145 }}
1146 }
1147
1148 and it'll come out as
1149
1150 if (br== "n3") {
1151 // etc.
1152 }
1153
1154 which is what you want.
1155
1156 Shut Up!
1157 People sometimes try to put an initialization section at the top of
1158 their templates, like this:
1159
1160 { ...
1161 $var = 17;
1162 }
1163
1164 Then they complain because there is a 17 at the top of the output that
1165 they didn't want to have there.
1166
1167 Remember that a program fragment is replaced with its own return value,
1168 and that in Perl the return value of a code block is the value of the
1169 last expression that was evaluated, which in this case is 17. If it
1170 didn't do that, you wouldn't be able to write "{$recipient}" and have
1171 the recipient filled in.
1172
1173 To prevent the 17 from appearing in the output is very simple:
1174
1175 { ...
1176 $var = 17;
1177 '';
1178 }
1179
1180 Now the last expression evaluated yields the empty string, which is
1181 invisible. If you don't like the way this looks, use
1182
1183 { ...
1184 $var = 17;
1185 ($SILENTLY);
1186 }
1187
1188 instead. Presumably, $SILENTLY has no value, so nothing will be
1189 interpolated. This is what is known as a `trick'.
1190
1191 Compatibility
1192 Every effort has been made to make this module compatible with older
1193 versions. The only known exceptions follow:
1194
1195 The output format of the default "BROKEN" subroutine has changed twice,
1196 most recently between versions 1.31 and 1.40.
1197
1198 Starting in version 1.10, the $OUT variable is arrogated for a special
1199 meaning. If you had templates before version 1.10 that happened to use
1200 a variable named $OUT, you will have to change them to use some other
1201 variable or all sorts of strangeness will result.
1202
1203 Between versions 0.1b and 1.00 the behavior of the \ metacharacter
1204 changed. In 0.1b, \\ was special everywhere, and the template
1205 processor always replaced it with a single backslash before passing the
1206 code to Perl for evaluation. The rule now is more complicated but
1207 probably more convenient. See the section on backslash processing,
1208 below, for a full discussion.
1209
1210 Backslash Processing
1211 In "Text::Template" beta versions, the backslash was special whenever
1212 it appeared before a brace or another backslash. That meant that while
1213 "{"\n"}" did indeed generate a newline, "{"\\"}" did not generate a
1214 backslash, because the code passed to Perl for evaluation was "\" which
1215 is a syntax error. If you wanted a backslash, you would have had to
1216 write "{"\\\\"}".
1217
1218 In "Text::Template" versions 1.00 through 1.10, there was a bug:
1219 Backslash was special everywhere. In these versions, "{"\n"}"
1220 generated the letter "n".
1221
1222 The bug has been corrected in version 1.11, but I did not go back to
1223 exactly the old rule, because I did not like the idea of having to
1224 write "{"\\\\"}" to get one backslash. The rule is now more
1225 complicated to remember, but probably easier to use. The rule is now:
1226 Backslashes are always passed to Perl unchanged unless they occur as
1227 part of a sequence like "\\\\\\{" or "\\\\\\}". In these contexts,
1228 they are special; "\\" is replaced with "\", and "\{" and "\}" signal a
1229 literal brace.
1230
1231 Examples:
1232
1233 \{ foo \}
1234
1235 is not evaluated, because the "\" before the braces signals that they
1236 should be taken literally. The result in the output looks like this:
1237
1238 { foo }
1239
1240 This is a syntax error:
1241
1242 { "foo}" }
1243
1244 because "Text::Template" thinks that the code ends at the first "}",
1245 and then gets upset when it sees the second one. To make this work
1246 correctly, use
1247
1248 { "foo\}" }
1249
1250 This passes "foo}" to Perl for evaluation. Note there's no "\" in the
1251 evaluated code. If you really want a "\" in the evaluated code, use
1252
1253 { "foo\\\}" }
1254
1255 This passes "foo\}" to Perl for evaluation.
1256
1257 Starting with "Text::Template" version 1.20, backslash processing is
1258 disabled if you use the "DELIMITERS" option to specify alternative
1259 delimiter strings.
1260
1261 A short note about $Text::Template::ERROR
1262 In the past some people have fretted about `violating the package
1263 boundary' by examining a variable inside the "Text::Template" package.
1264 Don't feel this way. $Text::Template::ERROR is part of the published,
1265 official interface to this package. It is perfectly OK to inspect this
1266 variable. The interface is not going to change.
1267
1268 If it really, really bothers you, you can import a function called
1269 "TTerror" that returns the current value of the $ERROR variable. So
1270 you can say:
1271
1272 use Text::Template 'TTerror';
1273
1274 my $template = new Text::Template (SOURCE => $filename);
1275 unless ($template) {
1276 my $err = TTerror;
1277 die "Couldn't make template: $err; aborting";
1278 }
1279
1280 I don't see what benefit this has over just doing this:
1281
1282 use Text::Template;
1283
1284 my $template = new Text::Template (SOURCE => $filename)
1285 or die "Couldn't make template: $Text::Template::ERROR; aborting";
1286
1287 But if it makes you happy to do it that way, go ahead.
1288
1289 Sticky Widgets in Template Files
1290 The "CGI" module provides functions for `sticky widgets', which are
1291 form input controls that retain their values from one page to the next.
1292 Sometimes people want to know how to include these widgets into their
1293 template output.
1294
1295 It's totally straightforward. Just call the "CGI" functions from
1296 inside the template:
1297
1298 { $q->checkbox_group(NAME => 'toppings',
1299 LINEBREAK => true,
1300 COLUMNS => 3,
1301 VALUES => \@toppings,
1302 );
1303 }
1304
1305 Automatic preprocessing of program fragments
1306 It may be useful to preprocess the program fragments before they are
1307 evaluated. See "Text::Template::Preprocess" for more details.
1308
1309 Automatic postprocessing of template hunks
1310 It may be useful to process hunks of output before they are appended to
1311 the result text. For this, subclass and replace the
1312 "append_text_to_result" method. It is passed a list of pairs with
1313 these entries:
1314
1315 handle - a filehandle to which to print the desired output
1316 out - a ref to a string to which to append, to use if handle is not given
1317 text - the text that will be appended
1318 type - where the text came from: TEXT for literal text, PROG for code
1319
1321 Originally written by Mark Jason Dominus, Plover Systems (versions 0.01
1322 - 1.46)
1323
1324 Maintainership transferred to Michael Schout <mschout@cpan.org> in
1325 version 1.47
1326
1328 Many thanks to the following people for offering support,
1329 encouragement, advice, bug reports, and all the other good stuff.
1330
1331 David H. Adler / Joel Appelbaum / Klaus Arnhold / António Aragão /
1332 Kevin Atteson / Chris.Brezil / Mike Brodhead / Tom Brown / Dr. Frank
1333 Bucolo / Tim Bunce / Juan E. Camacho / Itamar Almeida de Carvalho /
1334 Joseph Cheek / Gene Damon / San Deng / Bob Dougherty / Marek Grac / Dan
1335 Franklin / gary at dls.net / Todd A. Green / Donald L. Greer Jr. /
1336 Michelangelo Grigni / Zac Hansen / Tom Henry / Jarko Hietaniemi / Matt
1337 X. Hunter / Robert M. Ioffe / Daniel LaLiberte / Reuven M. Lerner /
1338 Trip Lilley / Yannis Livassof / Val Luck / Kevin Madsen / David
1339 Marshall / James Mastros / Joel Meulenberg / Jason Moore / Sergey
1340 Myasnikov / Chris Nandor / Bek Oberin / Steve Palincsar / Ron Pero /
1341 Hans Persson / Sean Roehnelt / Jonathan Roy / Shabbir J. Safdar /
1342 Jennifer D. St Clair / Uwe Schneider / Randal L. Schwartz / Michael G
1343 Schwern / Yonat Sharon / Brian C. Shensky / Niklas Skoglund / Tom Snee
1344 / Fred Steinberg / Hans Stoop / Michael J. Suzio / Dennis Taylor /
1345 James H. Thompson / Shad Todd / Lieven Tomme / Lorenzo Valdettaro /
1346 Larry Virden / Andy Wardley / Archie Warnock / Chris Wesley / Matt
1347 Womer / Andrew G Wood / Daini Xie / Michaely Yeung
1348
1349 Special thanks to:
1350
1351 Jonathan Roy
1352 for telling me how to do the "Safe" support (I spent two years
1353 worrying about it, and then Jonathan pointed out that it was
1354 trivial.)
1355
1356 Ranjit Bhatnagar
1357 for demanding less verbose fragments like they have in ASP, for
1358 helping me figure out the Right Thing, and, especially, for talking
1359 me out of adding any new syntax. These discussions resulted in the
1360 $OUT feature.
1361
1362 Bugs and Caveats
1363 "my" variables in "fill_in" are still susceptible to being clobbered by
1364 template evaluation. They all begin with "fi_", so avoid those names
1365 in your templates.
1366
1367 The line number information will be wrong if the template's lines are
1368 not terminated by "\n". You should let me know if this is a problem.
1369 If you do, I will fix it.
1370
1371 The $OUT variable has a special meaning in templates, so you cannot use
1372 it as if it were a regular variable.
1373
1374 There are not quite enough tests in the test suite.
1375
1377 The development version is on github at
1378 <http://https://github.com/mschout/perl-text-template> and may be
1379 cloned from <git://https://github.com/mschout/perl-text-template.git>
1380
1382 Please report any bugs or feature requests on the bugtracker website
1383 <https://github.com/mschout/perl-text-template/issues>
1384
1385 When submitting a bug or request, please include a test-file or a patch
1386 to an existing test-file that illustrates the bug or desired feature.
1387
1389 Michael Schout <mschout@cpan.org>
1390
1392 This software is copyright (c) 2013 by Mark Jason Dominus
1393 <mjd@cpan.org>.
1394
1395 This is free software; you can redistribute it and/or modify it under
1396 the same terms as the Perl 5 programming language system itself.
1397
1398
1399
1400perl v5.26.3 2018-03-04 Text::Template(3)