6 # Copyright 2013 M. J. Dominus.
7 # You may copy and distribute this program under the
8 # same terms as Perl iteself.
9 # If in doubt, write to mjd-perl-template+@plover.com for a license.
13 package Text::Template;
17 @EXPORT_OK = qw(fill_in_file fill_in_string TTerror);
21 $Text::Template::VERSION = '1.46';
22 my %GLOBAL_PREPEND = ('Text::Template' => '');
25 $Text::Template::VERSION;
31 for $kk ($k, "\u$k", "\U$k", "-$k", "-\u$k", "-\U$k") {
32 return $h{$kk} if exists $h{$kk};
40 my $old = $GLOBAL_PREPEND{$pack};
41 $GLOBAL_PREPEND{$pack} = shift;
48 %LEGAL_TYPE = map {$_=>1} qw(FILE FILEHANDLE STRING ARRAY);
53 my $stype = uc(_param('type', %a) || "FILE");
54 my $source = _param('source', %a);
55 my $untaint = _param('untaint', %a);
56 my $prepend = _param('prepend', %a);
57 my $alt_delim = _param('delimiters', %a);
58 my $broken = _param('broken', %a);
59 unless (defined $source) {
61 Carp::croak("Usage: $ {pack}::new(TYPE => ..., SOURCE => ...)");
63 unless ($LEGAL_TYPE{$stype}) {
65 Carp::croak("Illegal value `$stype' for TYPE parameter");
67 my $self = {TYPE => $stype,
71 (defined $alt_delim ? (DELIM => $alt_delim) : ()),
73 # Under 5.005_03, if any of $stype, $prepend, $untaint, or $broken
74 # are tainted, all the others become tainted too as a result of
75 # sharing the expression with them. We install $source separately
76 # to prevent it from acquiring a spurious taint.
77 $self->{SOURCE} = $source;
80 return unless $self->_acquire_data;
86 # Convert template objects of various types to type STRING,
87 # in which the template data is embedded in the object itself.
90 my $type = $self->{TYPE};
91 if ($type eq 'STRING') {
93 } elsif ($type eq 'FILE') {
94 my $data = _load_text($self->{SOURCE});
95 unless (defined $data) {
96 # _load_text already set $ERROR
99 if ($self->{UNTAINT} && _is_clean($self->{SOURCE})) {
100 _unconditionally_untaint($data);
102 $self->{TYPE} = 'STRING';
103 $self->{FILENAME} = $self->{SOURCE};
104 $self->{SOURCE} = $data;
105 } elsif ($type eq 'ARRAY') {
106 $self->{TYPE} = 'STRING';
107 $self->{SOURCE} = join '', @{$self->{SOURCE}};
108 } elsif ($type eq 'FILEHANDLE') {
109 $self->{TYPE} = 'STRING';
111 my $fh = $self->{SOURCE};
112 my $data = <$fh>; # Extra assignment avoids bug in Solaris perl5.00[45].
113 if ($self->{UNTAINT}) {
114 _unconditionally_untaint($data);
116 $self->{SOURCE} = $data;
118 # This should have been caught long ago, so it represents a
119 # drastic `can't-happen' sort of failure
120 my $pack = ref $self;
121 die "Can only acquire data for $pack objects of subtype STRING, but this is $type; aborting";
123 $self->{DATA_ACQUIRED} = 1;
128 $self->_acquire_data unless $self->{DATA_ACQUIRED};
129 return $self->{SOURCE};
132 sub set_source_data {
133 my ($self, $newdata) = @_;
134 $self->{SOURCE} = $newdata;
135 $self->{DATA_ACQUIRED} = 1;
136 $self->{TYPE} = 'STRING';
143 return 1 if $self->{TYPE} eq 'PREPARSED';
145 return undef unless $self->_acquire_data;
146 unless ($self->{TYPE} eq 'STRING') {
147 my $pack = ref $self;
148 # This should have been caught long ago, so it represents a
149 # drastic `can't-happen' sort of failure
150 die "Can only compile $pack objects of subtype STRING, but this is $self->{TYPE}; aborting";
154 my $delim_pats = shift() || $self->{DELIM};
158 my ($t_open, $t_close) = ('{', '}');
159 my $DELIM; # Regex matches a delimiter if $delim_pats
160 if (defined $delim_pats) {
161 ($t_open, $t_close) = @$delim_pats;
162 $DELIM = "(?:(?:\Q$t_open\E)|(?:\Q$t_close\E))";
163 @tokens = split /($DELIM|\n)/, $self->{SOURCE};
165 @tokens = split /(\\\\(?=\\*[{}])|\\[{}]|[{}\n])/, $self->{SOURCE};
174 my $t = shift @tokens;
176 if ($t eq $t_open) { # Brace or other opening delimiter
178 push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
181 $prog_start = $lineno;
186 } elsif ($t eq $t_close) { # Brace or other closing delimiter
189 $ERROR = "Unmatched close brace at line $lineno";
191 } elsif ($depth == 0) {
192 push @content, [$state, $cur_item, $prog_start] if $cur_item ne '';
198 } elsif (!$delim_pats && $t eq '\\\\') { # precedes \\\..\\\{ or \\\..\\\}
200 } elsif (!$delim_pats && $t =~ /^\\([{}])$/) { # Escaped (literal) brace?
202 } elsif ($t eq "\n") { # Newline
205 } else { # Anything else
210 if ($state eq 'PROG') {
211 $ERROR = "End of data inside program text that began at line $prog_start";
213 } elsif ($state eq 'TEXT') {
214 push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
216 die "Can't happen error #1";
219 $self->{TYPE} = 'PREPARSED';
220 $self->{SOURCE} = \@content;
226 my $t = $self->{PREPEND};
227 unless (defined $t) {
228 $t = $GLOBAL_PREPEND{ref $self};
229 unless (defined $t) {
230 $t = $GLOBAL_PREPEND{'Text::Template'};
233 $self->{PREPEND} = $_[1] if $#_ >= 1;
241 unless ($fi_self->{TYPE} eq 'PREPARSED') {
242 my $delims = _param('delimiters', %fi_a);
243 my @delim_arg = (defined $delims ? ($delims) : ());
244 $fi_self->compile(@delim_arg)
248 my $fi_varhash = _param('hash', %fi_a);
249 my $fi_package = _param('package', %fi_a) ;
251 _param('broken', %fi_a) || $fi_self->{BROKEN} || \&_default_broken;
252 my $fi_broken_arg = _param('broken_arg', %fi_a) || [];
253 my $fi_safe = _param('safe', %fi_a);
254 my $fi_ofh = _param('output', %fi_a);
256 my $fi_scrub_package = 0;
257 my $fi_filename = _param('filename') || $fi_self->{FILENAME} || 'template';
259 my $fi_prepend = _param('prepend', %fi_a);
260 unless (defined $fi_prepend) {
261 $fi_prepend = $fi_self->prepend_text;
264 if (defined $fi_safe) {
265 $fi_eval_package = 'main';
266 } elsif (defined $fi_package) {
267 $fi_eval_package = $fi_package;
268 } elsif (defined $fi_varhash) {
269 $fi_eval_package = _gensym();
270 $fi_scrub_package = 1;
272 $fi_eval_package = caller;
275 my $fi_install_package;
276 if (defined $fi_varhash) {
277 if (defined $fi_package) {
278 $fi_install_package = $fi_package;
279 } elsif (defined $fi_safe) {
280 $fi_install_package = $fi_safe->root;
282 $fi_install_package = $fi_eval_package; # The gensymmed one
284 _install_hash($fi_varhash => $fi_install_package);
287 if (defined $fi_package && defined $fi_safe) {
289 # Big fat magic here: Fix it so that the user-specified package
290 # is the default one available in the safe compartment.
291 *{$fi_safe->root . '::'} = \%{$fi_package . '::'}; # LOD
296 foreach $fi_item (@{$fi_self->{SOURCE}}) {
297 my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
298 if ($fi_type eq 'TEXT') {
299 $fi_self->append_text_to_output(
305 } elsif ($fi_type eq 'PROG') {
307 my $fi_lcomment = "#line $fi_lineno $fi_filename";
309 "package $fi_eval_package; $fi_prepend;\n$fi_lcomment\n$fi_text;";
311 my $fi_eval_err = '';
313 $fi_safe->reval(q{undef $OUT});
314 $fi_res = $fi_safe->reval($fi_progtext);
316 my $OUT = $fi_safe->reval('$OUT');
317 $fi_res = $OUT if defined $OUT;
320 $fi_res = eval $fi_progtext;
322 $fi_res = $OUT if defined $OUT;
325 # If the value of the filled-in text really was undef,
326 # change it to an explicit empty string to avoid undefined
327 # value warnings later.
328 $fi_res = '' unless defined $fi_res;
331 $fi_res = $fi_broken->(text => $fi_text,
332 error => $fi_eval_err,
333 lineno => $fi_lineno,
334 arg => $fi_broken_arg,
336 if (defined $fi_res) {
337 $fi_self->append_text_to_output(
344 return $fi_res; # Undefined means abort processing
347 $fi_self->append_text_to_output(
355 die "Can't happen error #2";
359 _scrubpkg($fi_eval_package) if $fi_scrub_package;
360 defined $fi_ofh ? 1 : $fi_r;
363 sub append_text_to_output {
364 my ($self, %arg) = @_;
366 if (defined $arg{handle}) {
367 print { $arg{handle} } $arg{text};
369 ${ $arg{out} } .= $arg{text};
378 my $templ = $pack->new(TYPE => 'STRING', SOURCE => $text, @_)
380 $templ->compile or return undef;
381 my $result = $templ->fill_in(@_);
387 my $package = _param('package', @_);
388 push @_, 'package' => scalar(caller) unless defined $package;
389 Text::Template->fill_this_in($string, @_);
394 my $templ = Text::Template->new(TYPE => 'FILE', SOURCE => $fn, @_)
396 $templ->compile or return undef;
397 my $text = $templ->fill_in(@_);
401 sub _default_broken {
403 my $prog_text = $a{text};
405 my $lineno = $a{lineno};
407 # $err =~ s/\s+at .*//s;
408 "Program fragment delivered error ``$err''";
414 unless (open F, $fn) {
415 $ERROR = "Couldn't open file $fn: $!";
424 eval { ($z = join('', @_)), eval '#' . substr($z,0,0); 1 } # LOD
427 sub _unconditionally_untaint {
436 __PACKAGE__ . '::GEN' . $seqno++;
440 $s =~ s/^Text::Template:://;
442 my $hash = $Text::Template::{$s."::"};
443 foreach my $key (keys %$hash) {
449 # Given a hashful of variables (or a list of such hashes)
450 # install the variables into the specified package,
451 # overwriting whatever variables were there before.
453 my $hashlist = shift;
455 if (UNIVERSAL::isa($hashlist, 'HASH')) {
456 $hashlist = [$hashlist];
459 foreach $hash (@$hashlist) {
461 foreach $name (keys %$hash) {
462 my $val = $hash->{$name};
464 local *SYM = *{"$ {dest}::$name"};
465 if (! defined $val) {
466 delete ${"$ {dest}::"}{$name};
476 sub TTerror { $ERROR }
483 Text::Template - Expand template text with embedded Perl
487 This file documents C<Text::Template> version B<1.46>
494 $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'filename.tmpl');
495 $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] );
496 $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh );
497 $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' );
498 $template = Text::Template->new(PREPEND => q{use strict;}, ...);
500 # Use a different template file syntax:
501 $template = Text::Template->new(DELIMITERS => [$open, $close], ...);
504 $text = $template->fill_in(); # Replaces `{$recipient}' with `King'
507 $T::recipient = 'Josh';
508 $text = $template->fill_in(PACKAGE => T);
510 # Pass many variables explicitly
511 $hash = { recipient => 'Abed-Nego',
512 friends => [ 'me', 'you' ],
513 enemies => { loathsome => 'Bill Gates',
514 fearsome => 'Larry Ellison' },
516 $text = $template->fill_in(HASH => $hash, ...);
517 # $recipient is Abed-Nego,
518 # @friends is ( 'me', 'you' ),
519 # %enemies is ( loathsome => ..., fearsome => ... )
522 # Call &callback in case of programming errors in template
523 $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...);
525 # Evaluate program fragments in Safe compartment with restricted permissions
526 $text = $template->fill_in(SAFE => $compartment, ...);
528 # Print result text instead of returning it
529 $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...);
531 # Parse template with different template file syntax:
532 $text = $template->fill_in(DELIMITERS => [$open, $close], ...);
533 # Note that this is *faster* than using the default delimiters
535 # Prepend specified perl code to each fragment before evaluating:
536 $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...);
538 use Text::Template 'fill_in_string';
539 $text = fill_in_string( <<EOM, PACKAGE => 'T', ...);
546 use Text::Template 'fill_in_file';
547 $text = fill_in_file($filename, ...);
549 # All templates will always have `use strict vars' attached to all fragments
550 Text::Template->always_prepend(q{use strict 'vars';});
554 This is a library for generating form letters, building HTML pages, or
555 filling in templates generally. A `template' is a piece of text that
556 has little Perl programs embedded in it here and there. When you
557 `fill in' a template, you evaluate the little programs and replace
558 them with their values.
560 You can store a template in a file outside your program. People can
561 modify the template without modifying the program. You can separate
562 the formatting details from the main code, and put the formatting
563 parts of the program into the template. That prevents code bloat and
564 encourages functional separation.
568 Here's an example of a template, which we'll suppose is stored in the
569 file C<formletter.tmpl>:
571 Dear {$title} {$lastname},
573 It has come to our attention that you are delinquent in your
574 {$monthname[$last_paid_month]} payment. Please remit
575 ${sprintf("%.2f", $amount)} immediately, or your patellae may
576 be needlessly endangered.
580 Mark "Vizopteryx" Dominus
583 The result of filling in this template is a string, which might look
588 It has come to our attention that you are delinquent in your
589 February payment. Please remit
590 $392.12 immediately, or your patellae may
591 be needlessly endangered.
596 Mark "Vizopteryx" Dominus
598 Here is a complete program that transforms the example
599 template into the example result, and prints it out:
603 my $template = Text::Template->new(SOURCE => 'formletter.tmpl')
604 or die "Couldn't construct template: $Text::Template::ERROR";
606 my @monthname = qw(January February March April May June
607 July August September October November December);
608 my %vars = (title => 'Mr.',
611 last_paid_month => 1, # February
613 monthname => \@monthname,
616 my $result = $template->fill_in(HASH => \%vars);
618 if (defined $result) { print $result }
619 else { die "Couldn't fill in template: $Text::Template::ERROR" }
624 When people make a template module like this one, they almost always
625 start by inventing a special syntax for substitutions. For example,
626 they build it so that a string like C<%%VAR%%> is replaced with the
627 value of C<$VAR>. Then they realize the need extra formatting, so
628 they put in some special syntax for formatting. Then they need a
629 loop, so they invent a loop syntax. Pretty soon they have a new
630 little template language.
632 This approach has two problems: First, their little language is
633 crippled. If you need to do something the author hasn't thought of,
634 you lose. Second: Who wants to learn another language? You already
635 know Perl, so why not use it?
637 C<Text::Template> templates are programmed in I<Perl>. You embed Perl
638 code in your template, with C<{> at the beginning and C<}> at the end.
639 If you want a variable interpolated, you write it the way you would in
640 Perl. If you need to make a loop, you can use any of the Perl loop
641 constructions. All the Perl built-in functions are available.
645 =head2 Template Parsing
647 The C<Text::Template> module scans the template source. An open brace
648 C<{> begins a program fragment, which continues until the matching
649 close brace C<}>. When the template is filled in, the program
650 fragments are evaluated, and each one is replaced with the resulting
651 value to yield the text that is returned.
653 A backslash C<\> in front of a brace (or another backslash that is in
654 front of a brace) escapes its special meaning. The result of filling
657 \{ The sum of 1 and 2 is {1+2} \}
661 { The sum of 1 and 2 is 3 }
663 If you have an unmatched brace, C<Text::Template> will return a
664 failure code and a warning about where the problem is. Backslashes
665 that do not precede a brace are passed through unchanged. If you have
666 a template like this:
668 { "String that ends in a newline.\n" }
670 The backslash inside the string is passed through to Perl unchanged,
671 so the C<\n> really does turn into a newline. See the note at the end
672 for details about the way backslashes work. Backslash processing is
673 I<not> done when you specify alternative delimiters with the
674 C<DELIMITERS> option. (See L<"Alternative Delimiters">, below.)
676 Each program fragment should be a sequence of Perl statements, which
677 are evaluated the usual way. The result of the last statement
678 executed will be evaluted in scalar context; the result of this
679 statement is a string, which is interpolated into the template in
680 place of the program fragment itself.
682 The fragments are evaluated in order, and side effects from earlier
683 fragments will persist into later fragments:
685 {$x = @things; ''}The Lord High Chamberlain has gotten {$x}
686 things for me this year.
691 } elsif ($diff < 0) {
696 That is {$diff} {$more} than he gave me last year.
698 The value of C<$x> set in the first line will persist into the next
699 fragment that begins on the third line, and the values of C<$diff> and
700 C<$more> set in the second fragment will persist and be interpolated
701 into the last line. The output will look something like this:
703 The Lord High Chamberlain has gotten 42
704 things for me this year.
706 That is 25 more than he gave me last year.
708 That is all the syntax there is.
710 =head2 The C<$OUT> variable
712 There is one special trick you can play in a template. Here is the
713 motivation for it: Suppose you are going to pass an array, C<@items>,
714 into the template, and you want the template to generate a bulleted
715 list with a header, like this:
717 Here is a list of the things I have got for you since 1907:
723 One way to do it is with a template like this:
725 Here is a list of the things I have got for you since 1907:
727 foreach $i (@items) {
728 $blist .= qq{ * $i\n};
733 Here we construct the list in a variable called C<$blist>, which we
734 return at the end. This is a little cumbersome. There is a shortcut.
736 Inside of templates, there is a special variable called C<$OUT>.
737 Anything you append to this variable will appear in the output of the
738 template. Also, if you use C<$OUT> in a program fragment, the normal
739 behavior, of replacing the fragment with its return value, is
740 disabled; instead the fragment is replaced with the value of C<$OUT>.
741 This means that you can write the template above like this:
743 Here is a list of the things I have got for you since 1907:
744 { foreach $i (@items) {
749 C<$OUT> is reinitialized to the empty string at the start of each
750 program fragment. It is private to C<Text::Template>, so
751 you can't use a variable named C<$OUT> in your template without
752 invoking the special behavior.
754 =head2 General Remarks
756 All C<Text::Template> functions return C<undef> on failure, and set the
757 variable C<$Text::Template::ERROR> to contain an explanation of what
758 went wrong. For example, if you try to create a template from a file
759 that does not exist, C<$Text::Template::ERROR> will contain something like:
761 Couldn't open file xyz.tmpl: No such file or directory
765 $template = new Text::Template ( TYPE => ..., SOURCE => ... );
767 This creates and returns a new template object. C<new> returns
768 C<undef> and sets C<$Text::Template::ERROR> if it can't create the
769 template object. C<SOURCE> says where the template source code will
770 come from. C<TYPE> says what kind of object the source is.
772 The most common type of source is a file:
774 new Text::Template ( TYPE => 'FILE', SOURCE => $filename );
776 This reads the template from the specified file. The filename is
777 opened with the Perl C<open> command, so it can be a pipe or anything
778 else that makes sense with C<open>.
780 The C<TYPE> can also be C<STRING>, in which case the C<SOURCE> should
783 new Text::Template ( TYPE => 'STRING',
784 SOURCE => "This is the actual template!" );
786 The C<TYPE> can be C<ARRAY>, in which case the source should be a
787 reference to an array of strings. The concatenation of these strings
790 new Text::Template ( TYPE => 'ARRAY',
791 SOURCE => [ "This is ", "the actual",
796 The C<TYPE> can be FILEHANDLE, in which case the source should be an
797 open filehandle (such as you got from the C<FileHandle> or C<IO::*>
798 packages, or a glob, or a reference to a glob). In this case
799 C<Text::Template> will read the text from the filehandle up to
800 end-of-file, and that text is the template:
802 # Read template source code from STDIN:
803 new Text::Template ( TYPE => 'FILEHANDLE',
807 If you omit the C<TYPE> attribute, it's taken to be C<FILE>.
808 C<SOURCE> is required. If you omit it, the program will abort.
810 The words C<TYPE> and C<SOURCE> can be spelled any of the following ways:
819 Pick a style you like and stick with it.
825 You may also add a C<DELIMITERS> option. If this option is present,
826 its value should be a reference to an array of two strings. The first
827 string is the string that signals the beginning of each program
828 fragment, and the second string is the string that signals the end of
829 each program fragment. See L<"Alternative Delimiters">, below.
833 If your program is running in taint mode, you may have problems if
834 your templates are stored in files. Data read from files is
835 considered 'untrustworthy', and taint mode will not allow you to
836 evaluate the Perl code in the file. (It is afraid that a malicious
837 person might have tampered with the file.)
839 In some environments, however, local files are trustworthy. You can
840 tell C<Text::Template> that a certain file is trustworthy by supplying
841 C<UNTAINT =E<gt> 1> in the call to C<new>. This will tell
842 C<Text::Template> to disable taint checks on template code that has
843 come from a file, as long as the filename itself is considered
844 trustworthy. It will also disable taint checks on template code that
845 comes from a filehandle. When used with C<TYPE =E<gt> 'string'> or C<TYPE
846 =E<gt> 'array'>, it has no effect.
848 See L<perlsec> for more complete information about tainting.
850 Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph Baehr
851 for help with this feature.
855 This option is passed along to the C<fill_in> call unless it is
856 overridden in the arguments to C<fill_in>. See L<C<PREPEND> feature
857 and using C<strict> in templates> below.
861 This option is passed along to the C<fill_in> call unless it is
862 overridden in the arguments to C<fill_in>. See L<C<BROKEN>> below.
870 Loads all the template text from the template's source, parses and
871 compiles it. If successful, returns true; otherwise returns false and
872 sets C<$Text::Template::ERROR>. If the template is already compiled,
873 it returns true and does nothing.
875 You don't usually need to invoke this function, because C<fill_in>
876 (see below) compiles the template if it isn't compiled already.
878 If there is an argument to this function, it must be a reference to an
879 array containing alternative delimiter strings. See C<"Alternative
884 $template->fill_in(OPTIONS);
886 Fills in a template. Returns the resulting text if successful.
887 Otherwise, returns C<undef> and sets C<$Text::Template::ERROR>.
889 The I<OPTIONS> are a hash, or a list of key-value pairs. You can
890 write the key names in any of the six usual styles as above; this
891 means that where this manual says C<PACKAGE> (for example) you can
894 PACKAGE Package package -PACKAGE -Package -package
896 Pick a style you like and stick with it. The all-lowercase versions
897 may yield spurious warnings about
899 Ambiguous use of package => resolved to "package"
901 so you might like to avoid them and use the capitalized versions.
903 At present, there are eight legal options: C<PACKAGE>, C<BROKEN>,
904 C<BROKEN_ARG>, C<SAFE>, C<HASH>, C<OUTPUT>, and C<DELIMITERS>.
910 C<PACKAGE> specifies the name of a package in which the program
911 fragments should be evaluated. The default is to use the package from
912 which C<fill_in> was called. For example, consider this template:
914 The value of the variable x is {$x}.
916 If you use C<$template-E<gt>fill_in(PACKAGE =E<gt> 'R')> , then the C<$x> in
917 the template is actually replaced with the value of C<$R::x>. If you
918 omit the C<PACKAGE> option, C<$x> will be replaced with the value of
919 the C<$x> variable in the package that actually called C<fill_in>.
921 You should almost always use C<PACKAGE>. If you don't, and your
922 template makes changes to variables, those changes will be propagated
923 back into the main program. Evaluating the template in a private
924 package helps prevent this. The template can still modify variables
925 in your program if it wants to, but it will have to do so explicitly.
926 See the section at the end on `Security'.
928 Here's an example of using C<PACKAGE>:
932 Enclosed please find a list of things I have gotten
935 { foreach $item (@items) {
937 $OUT .= " $item_no. \u$item\n";
942 Lord High Chamberlain
944 We want to pass in an array which will be assigned to the array
945 C<@items>. Here's how to do that:
948 @items = ('ivory', 'apes', 'peacocks', );
949 $template->fill_in();
951 This is not very safe. The reason this isn't as safe is that if you
952 had a variable named C<$item_no> in scope in your program at the point
953 you called C<fill_in>, its value would be clobbered by the act of
954 filling out the template. The problem is the same as if you had
955 written a subroutine that used those variables in the same way that
956 the template does. (C<$OUT> is special in templates and is always
959 One solution to this is to make the C<$item_no> variable private to the
960 template by declaring it with C<my>. If the template does this, you
963 But if you use the C<PACKAGE> option, you will probably be safe even
964 if the template does I<not> declare its variables with C<my>:
966 @Q::items = ('ivory', 'apes', 'peacocks', );
967 $template->fill_in(PACKAGE => 'Q');
969 In this case the template will clobber the variable C<$Q::item_no>,
970 which is not related to the one your program was using.
972 Templates cannot affect variables in the main program that are
973 declared with C<my>, unless you give the template references to those
978 You may not want to put the template variables into a package.
979 Packages can be hard to manage: You can't copy them, for example.
980 C<HASH> provides an alternative.
982 The value for C<HASH> should be a reference to a hash that maps
983 variable names to values. For example,
985 $template->fill_in(HASH => { recipient => "The King",
986 items => ['gold', 'frankincense', 'myrrh'],
990 will fill out the template and use C<"The King"> as the value of
991 C<$recipient> and the list of items as the value of C<@items>. Note
992 that we pass an array reference, but inside the template it appears as
993 an array. In general, anything other than a simple string or number
994 should be passed by reference.
996 We also want to pass an object, which is in C<$self>; note that we
997 pass a reference to the object, C<\$self> instead. Since we've passed
998 a reference to a scalar, inside the template the object appears as
1001 The full details of how it works are a little involved, so you might
1002 want to skip to the next section.
1004 Suppose the key in the hash is I<key> and the value is I<value>.
1010 If the I<value> is C<undef>, then any variables named C<$key>,
1011 C<@key>, C<%key>, etc., are undefined.
1015 If the I<value> is a string or a number, then C<$key> is set to that
1016 value in the template.
1020 For anything else, you must pass a reference.
1022 If the I<value> is a reference to an array, then C<@key> is set to
1023 that array. If the I<value> is a reference to a hash, then C<%key> is
1024 set to that hash. Similarly if I<value> is any other kind of
1025 reference. This means that
1033 have almost exactly the same effect. (The difference is that in the
1034 former case, the value is copied, and in the latter case it is
1039 In particular, if you want the template to get an object or any kind,
1040 you must pass a reference to it:
1042 $template->fill_in(HASH => { database_handle => \$dbh, ... });
1044 If you do this, the template will have a variable C<$database_handle>
1045 which is the database handle object. If you leave out the C<\>, the
1046 template will have a hash C<%database_handle>, which exposes the
1047 internal structure of the database handle object; you don't want that.
1051 Normally, the way this works is by allocating a private package,
1052 loading all the variables into the package, and then filling out the
1053 template as if you had specified that package. A new package is
1054 allocated each time. However, if you I<also> use the C<PACKAGE>
1055 option, C<Text::Template> loads the variables into the package you
1056 specified, and they stay there after the call returns. Subsequent
1057 calls to C<fill_in> that use the same package will pick up the values
1060 If the argument of C<HASH> is a reference to an array instead of a
1061 reference to a hash, then the array should contain a list of hashes
1062 whose contents are loaded into the template package one after the
1063 other. You can use this feature if you want to combine several sets
1064 of variables. For example, one set of variables might be the defaults
1065 for a fill-in form, and the second set might be the user inputs, which
1066 override the defaults when they are present:
1068 $template->fill_in(HASH => [\%defaults, \%user_input]);
1070 You can also use this to set two variables with the same name:
1072 $template->fill_in(HASH => [{ v => "The King" },
1077 This sets C<$v> to C<"The King"> and C<@v> to C<(1,2,3)>.
1081 If any of the program fragments fails to compile or aborts for any
1082 reason, and you have set the C<BROKEN> option to a function reference,
1083 C<Text::Template> will invoke the function. This function is called
1084 the I<C<BROKEN> function>. The C<BROKEN> function will tell
1085 C<Text::Template> what to do next.
1087 If the C<BROKEN> function returns C<undef>, C<Text::Template> will
1088 immediately abort processing the template and return the text that it
1089 has accumulated so far. If your function does this, it should set a
1090 flag that you can examine after C<fill_in> returns so that you can
1091 tell whether there was a premature return or not.
1093 If the C<BROKEN> function returns any other value, that value will be
1094 interpolated into the template as if that value had been the return
1095 value of the program fragment to begin with. For example, if the
1096 C<BROKEN> function returns an error string, the error string will be
1097 interpolated into the output of the template in place of the program
1098 fragment that cased the error.
1100 If you don't specify a C<BROKEN> function, C<Text::Template> supplies
1101 a default one that returns something like
1103 Program fragment delivered error ``Illegal division by 0 at
1106 (Note that the format of this message has changed slightly since
1107 version 1.31.) The return value of the C<BROKEN> function is
1108 interpolated into the template at the place the error occurred, so
1111 (3+4)*5 = { 3+4)*5 }
1115 (3+4)*5 = Program fragment delivered error ``syntax error at template line 1''
1117 If you specify a value for the C<BROKEN> attribute, it should be a
1118 reference to a function that C<fill_in> can call instead of the
1121 C<fill_in> will pass a hash to the C<broken> function.
1122 The hash will have at least these three members:
1128 The source code of the program fragment that failed
1132 The text of the error message (C<$@>) generated by eval.
1134 The text has been modified to omit the trailing newline and to include
1135 the name of the template file (if there was one). The line number
1136 counts from the beginning of the template, not from the beginning of
1137 the failed program fragment.
1141 The line number of the template at which the program fragment began.
1145 There may also be an C<arg> member. See C<BROKEN_ARG>, below
1149 If you supply the C<BROKEN_ARG> option to C<fill_in>, the value of the
1150 option is passed to the C<BROKEN> function whenever it is called. The
1151 default C<BROKEN> function ignores the C<BROKEN_ARG>, but you can
1152 write a custom C<BROKEN> function that uses the C<BROKEN_ARG> to get
1153 more information about what went wrong.
1155 The C<BROKEN> function could also use the C<BROKEN_ARG> as a reference
1156 to store an error message or some other information that it wants to
1157 communicate back to the caller. For example:
1163 my $err_ref = $args{arg};
1165 $$err_ref = "Some error message";
1169 $template->fill_in(BROKEN => \&my_broken,
1170 BROKEN_ARG => \$error,
1174 die "It didn't work: $error";
1177 If one of the program fragments in the template fails, it will call
1178 the C<BROKEN> function, C<my_broken>, and pass it the C<BROKEN_ARG>,
1179 which is a reference to C<$error>. C<my_broken> can store an error
1180 message into C<$error> this way. Then the function that called
1181 C<fill_in> can see if C<my_broken> has left an error message for it
1182 to find, and proceed accordingly.
1186 If you give C<fill_in> a C<SAFE> option, its value should be a safe
1187 compartment object from the C<Safe> package. All evaluation of
1188 program fragments will be performed in this compartment. See L<Safe>
1189 for full details about such compartments and how to restrict the
1190 operations that can be performed in them.
1192 If you use the C<PACKAGE> option with C<SAFE>, the package you specify
1193 will be placed into the safe compartment and evaluation will take
1194 place in that package as usual.
1196 If not, C<SAFE> operation is a little different from the default.
1197 Usually, if you don't specify a package, evaluation of program
1198 fragments occurs in the package from which the template was invoked.
1199 But in C<SAFE> mode the evaluation occurs inside the safe compartment
1200 and cannot affect the calling package. Normally, if you use C<HASH>
1201 without C<PACKAGE>, the hash variables are imported into a private,
1202 one-use-only package. But if you use C<HASH> and C<SAFE> together
1203 without C<PACKAGE>, the hash variables will just be loaded into the
1204 root namespace of the C<Safe> compartment.
1208 If your template is going to generate a lot of text that you are just
1209 going to print out again anyway, you can save memory by having
1210 C<Text::Template> print out the text as it is generated instead of
1211 making it into a big string and returning the string. If you supply
1212 the C<OUTPUT> option to C<fill_in>, the value should be a filehandle.
1213 The generated text will be printed to this filehandle as it is
1214 constructed. For example:
1216 $template->fill_in(OUTPUT => \*STDOUT, ...);
1218 fills in the C<$template> as usual, but the results are immediately
1219 printed to STDOUT. This may result in the output appearing more
1220 quickly than it would have otherwise.
1222 If you use C<OUTPUT>, the return value from C<fill_in> is still true on
1223 success and false on failure, but the complete text is not returned to
1228 You can have some Perl code prepended automatically to the beginning
1229 of every program fragment. See L<C<PREPEND> feature and using
1230 C<strict> in templates> below.
1234 If this option is present, its value should be a reference to a list
1235 of two strings. The first string is the string that signals the
1236 beginning of each program fragment, and the second string is the
1237 string that signals the end of each program fragment. See
1238 L<"Alternative Delimiters">, below.
1240 If you specify C<DELIMITERS> in the call to C<fill_in>, they override
1241 any delimiters you set when you created the template object with
1246 =head1 Convenience Functions
1248 =head2 C<fill_this_in>
1250 The basic way to fill in a template is to create a template object and
1251 then call C<fill_in> on it. This is useful if you want to fill in
1252 the same template more than once.
1254 In some programs, this can be cumbersome. C<fill_this_in> accepts a
1255 string, which contains the template, and a list of options, which are
1256 passed to C<fill_in> as above. It constructs the template object for
1257 you, fills it in as specified, and returns the results. It returns
1258 C<undef> and sets C<$Text::Template::ERROR> if it couldn't generate
1263 $Q::name = 'Donald';
1264 $Q::amount = 141.61;
1265 $Q::part = 'hyoid bone';
1267 $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q);
1269 You owe me \\${sprintf('%.2f', $amount)}.
1270 Pay or I will break your {$part}.
1272 Grand Vizopteryx of Irkutsk.
1275 Notice how we included the template in-line in the program by using a
1276 `here document' with the C<E<lt>E<lt>> notation.
1278 C<fill_this_in> is a deprecated feature. It is only here for
1279 backwards compatibility, and may be removed in some far-future version
1280 in C<Text::Template>. You should use C<fill_in_string> instead. It
1281 is described in the next section.
1283 =head2 C<fill_in_string>
1285 It is stupid that C<fill_this_in> is a class method. It should have
1286 been just an imported function, so that you could omit the
1287 C<Text::Template-E<gt>> in the example above. But I made the mistake
1288 four years ago and it is too late to change it.
1290 C<fill_in_string> is exactly like C<fill_this_in> except that it is
1291 not a method and you can omit the C<Text::Template-E<gt>> and just say
1293 print fill_in_string(<<'EOM', ...);
1298 To use C<fill_in_string>, you need to say
1300 use Text::Template 'fill_in_string';
1302 at the top of your program. You should probably use
1303 C<fill_in_string> instead of C<fill_this_in>.
1305 =head2 C<fill_in_file>
1307 If you import C<fill_in_file>, you can say
1309 $text = fill_in_file(filename, ...);
1311 The C<...> are passed to C<fill_in> as above. The filename is the
1312 name of the file that contains the template you want to fill in. It
1313 returns the result text. or C<undef>, as usual.
1315 If you are going to fill in the same file more than once in the same
1316 program you should use the longer C<new> / C<fill_in> sequence instead.
1317 It will be a lot faster because it only has to read and parse the file
1320 =head2 Including files into templates
1322 People always ask for this. ``Why don't you have an include
1323 function?'' they want to know. The short answer is this is Perl, and
1324 Perl already has an include function. If you want it, you can just put
1328 into your template. VoilE<agrave>.
1330 If you don't want to use C<cat>, you can write a little four-line
1331 function that opens a file and dumps out its contents, and call it
1332 from the template. I wrote one for you. In the template, you can say
1334 {Text::Template::_load_text(filename)}
1336 If that is too verbose, here is a trick. Suppose the template package
1337 that you are going to be mentioning in the C<fill_in> call is package
1338 C<Q>. Then in the main program, write
1340 *Q::include = \&Text::Template::_load_text;
1342 This imports the C<_load_text> function into package C<Q> with the
1343 name C<include>. From then on, any template that you fill in with
1344 package C<Q> can say
1348 to insert the text from the named file at that point. If you are
1349 using the C<HASH> option instead, just put C<include =E<gt>
1350 \&Text::Template::_load_text> into the hash instead of importing it
1353 Suppose you don't want to insert a plain text file, but rather you
1354 want to include one template within another? Just use C<fill_in_file>
1355 in the template itself:
1357 {Text::Template::fill_in_file(filename)}
1359 You can do the same importing trick if this is too much to type.
1361 =head1 Miscellaneous
1363 =head2 C<my> variables
1365 People are frequently surprised when this doesn't work:
1367 my $recipient = 'The King';
1368 my $text = fill_in_file('formletter.tmpl');
1370 The text C<The King> doesn't get into the form letter. Why not?
1371 Because C<$recipient> is a C<my> variable, and the whole point of
1372 C<my> variables is that they're private and inaccessible except in the
1373 scope in which they're declared. The template is not part of that
1374 scope, so the template can't see C<$recipient>.
1376 If that's not the behavior you want, don't use C<my>. C<my> means a
1377 private variable, and in this case you don't want the variable to be
1378 private. Put the variables into package variables in some other
1379 package, and use the C<PACKAGE> option to C<fill_in>:
1381 $Q::recipient = $recipient;
1382 my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q');
1385 or pass the names and values in a hash with the C<HASH> option:
1387 my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient });
1389 =head2 Security Matters
1391 All variables are evaluated in the package you specify with the
1392 C<PACKAGE> option of C<fill_in>. if you use this option, and if your
1393 templates don't do anything egregiously stupid, you won't have to
1394 worry that evaluation of the little programs will creep out into the
1395 rest of your program and wreck something.
1397 Nevertheless, there's really no way (except with C<Safe>) to protect
1398 against a template that says
1400 { $Important::Secret::Security::Enable = 0;
1401 # Disable security checks in this program
1406 { $/ = "ho ho ho"; # Sabotage future uses of <FH>.
1407 # $/ is always a global variable
1412 { system("rm -rf /") }
1414 so B<don't> go filling in templates unless you're sure you know what's
1415 in them. If you're worried, or you can't trust the person who wrote
1416 the template, use the C<SAFE> option.
1418 A final warning: program fragments run a small risk of accidentally
1419 clobbering local variables in the C<fill_in> function itself. These
1420 variables all have names that begin with C<$fi_>, so if you stay away
1421 from those names you'll be safe. (Of course, if you're a real wizard
1422 you can tamper with them deliberately for exciting effects; this is
1423 actually how C<$OUT> works.) I can fix this, but it will make the
1424 package slower to do it, so I would prefer not to. If you are worried
1425 about this, send me mail and I will show you what to do about it.
1427 =head2 Alternative Delimiters
1429 Lorenzo Valdettaro pointed out that if you are using C<Text::Template>
1430 to generate TeX output, the choice of braces as the program fragment
1431 delimiters makes you suffer suffer suffer. Starting in version 1.20,
1432 you can change the choice of delimiters to something other than curly
1435 In either the C<new()> call or the C<fill_in()> call, you can specify
1436 an alternative set of delimiters with the C<DELIMITERS> option. For
1437 example, if you would like code fragments to be delimited by C<[@-->
1438 and C<--@]> instead of C<{> and C<}>, use
1440 ... DELIMITERS => [ '[@--', '--@]' ], ...
1442 Note that these delimiters are I<literal strings>, not regexes. (I
1443 tried for regexes, but it complicates the lexical analysis too much.)
1444 Note also that C<DELIMITERS> disables the special meaning of the
1445 backslash, so if you want to include the delimiters in the literal
1446 text of your template file, you are out of luck---it is up to you to
1447 choose delimiters that do not conflict with what you are doing. The
1448 delimiter strings may still appear inside of program fragments as long
1449 as they nest properly. This means that if for some reason you
1450 absolutely must have a program fragment that mentions one of the
1451 delimiters, like this:
1454 print "Oh no, a delimiter: --@]\n"
1457 you may be able to make it work by doing this instead:
1460 # Fake matching delimiter in a comment: [@--
1461 print "Oh no, a delimiter: --@]\n"
1464 It may be safer to choose delimiters that begin with a newline
1467 Because the parsing of templates is simplified by the absence of
1468 backslash escapes, using alternative C<DELIMITERS> may speed up the
1469 parsing process by 20-25%. This shows that my original choice of C<{>
1470 and C<}> was very bad.
1472 =head2 C<PREPEND> feature and using C<strict> in templates
1474 Suppose you would like to use C<strict> in your templates to detect
1475 undeclared variables and the like. But each code fragment is a
1476 separate lexical scope, so you have to turn on C<strict> at the top of
1477 each and every code fragment:
1487 { # we forgot to put `use strict' here
1488 my $result = $boo + 12; # $boo is misspelled and should be $foo
1489 # No error is raised on `$boo'
1492 Because we didn't put C<use strict> at the top of the second fragment,
1493 it was only active in the first fragment, and we didn't get any
1494 C<strict> checking in the second fragment. Then we mispelled C<$foo>
1495 and the error wasn't caught.
1497 C<Text::Template> version 1.22 and higher has a new feature to make
1498 this easier. You can specify that any text at all be automatically
1499 added to the beginning of each program fragment.
1501 When you make a call to C<fill_in>, you can specify a
1503 PREPEND => 'some perl statements here'
1505 option; the statements will be prepended to each program fragment for
1506 that one call only. Suppose that the C<fill_in> call included a
1508 PREPEND => 'use strict;'
1510 option, and that the template looked like this:
1519 { my $result = $boo + 12; # $boo is misspelled and should be $foo
1523 The code in the second fragment would fail, because C<$boo> has not
1524 been declared. C<use strict> was implied, even though you did not
1525 write it explicitly, because the C<PREPEND> option added it for you
1528 There are two other ways to do this. At the time you create the
1529 template object with C<new>, you can also supply a C<PREPEND> option,
1530 in which case the statements will be prepended each time you fill in
1531 that template. If the C<fill_in> call has its own C<PREPEND> option,
1532 this overrides the one specified at the time you created the
1533 template. Finally, you can make the class method call
1535 Text::Template->always_prepend('perl statements');
1537 If you do this, then call calls to C<fill_in> for I<any> template will
1538 attach the perl statements to the beginning of each program fragment,
1539 except where overridden by C<PREPEND> options to C<new> or C<fill_in>.
1541 =head2 Prepending in Derived Classes
1543 This section is technical, and you should skip it on the first few
1546 Normally there are three places that prepended text could come from.
1547 It could come from the C<PREPEND> option in the C<fill_in> call, from
1548 the C<PREPEND> option in the C<new> call that created the template
1549 object, or from the argument of the C<always_prepend> call.
1550 C<Text::Template> looks for these three things in order and takes the
1551 first one that it finds.
1553 In a subclass of C<Text::Template>, this last possibility is
1554 ambiguous. Suppose C<S> is a subclass of C<Text::Template>. Should
1556 Text::Template->always_prepend(...);
1558 affect objects in class C<Derived>? The answer is that you can have it
1561 The C<always_prepend> value for C<Text::Template> is normally stored
1562 in a hash variable named C<%GLOBAL_PREPEND> under the key
1563 C<Text::Template>. When C<Text::Template> looks to see what text to
1564 prepend, it first looks in the template object itself, and if not, it
1565 looks in C<$GLOBAL_PREPEND{I<class>}> where I<class> is the class to
1566 which the template object belongs. If it doesn't find any value, it
1567 looks in C<$GLOBAL_PREPEND{'Text::Template'}>. This means that
1568 objects in class C<Derived> I<will> be affected by
1570 Text::Template->always_prepend(...);
1572 I<unless> there is also a call to
1574 Derived->always_prepend(...);
1576 So when you're designing your derived class, you can arrange to have
1577 your objects ignore C<Text::Template::always_prepend> calls by simply
1578 putting C<Derived-E<gt>always_prepend('')> at the top of your module.
1580 Of course, there is also a final escape hatch: Templates support a
1581 C<prepend_text> that is used to look up the appropriate text to be
1582 prepended at C<fill_in> time. Your derived class can override this
1583 method to get an arbitrary effect.
1587 Jennifer D. St Clair asks:
1589 > Most of my pages contain JavaScript and Stylesheets.
1590 > How do I change the template identifier?
1592 Jennifer is worried about the braces in the JavaScript being taken as
1593 the delimiters of the Perl program fragments. Of course, disaster
1594 will ensue when perl tries to evaluate these as if they were Perl
1595 programs. The best choice is to find some unambiguous delimiter
1596 strings that you can use in your template instead of curly braces, and
1597 then use the C<DELIMITERS> option. However, if you can't do this for
1598 some reason, there are two easy workarounds:
1600 1. You can put C<\> in front of C<{>, C<}>, or C<\> to remove its
1601 special meaning. So, for example, instead of
1613 and it'll come out of the template engine the way you want.
1615 But here is another method that is probably better. To see how it
1616 works, first consider what happens if you put this into a template:
1620 Since it's in braces, it gets evaluated, and obviously, this is going
1625 So now here's the trick: In Perl, C<q{...}> is the same as C<'...'>.
1634 So for your JavaScript, just write
1641 and it'll come out as
1647 which is what you want.
1652 People sometimes try to put an initialization section at the top of
1653 their templates, like this:
1659 Then they complain because there is a C<17> at the top of the output
1660 that they didn't want to have there.
1662 Remember that a program fragment is replaced with its own return
1663 value, and that in Perl the return value of a code block is the value
1664 of the last expression that was evaluated, which in this case is 17.
1665 If it didn't do that, you wouldn't be able to write C<{$recipient}>
1666 and have the recipient filled in.
1668 To prevent the 17 from appearing in the output is very simple:
1675 Now the last expression evaluated yields the empty string, which is
1676 invisible. If you don't like the way this looks, use
1683 instead. Presumably, C<$SILENTLY> has no value, so nothing will be
1684 interpolated. This is what is known as a `trick'.
1686 =head2 Compatibility
1688 Every effort has been made to make this module compatible with older
1689 versions. The only known exceptions follow:
1691 The output format of the default C<BROKEN> subroutine has changed
1692 twice, most recently between versions 1.31 and 1.40.
1694 Starting in version 1.10, the C<$OUT> variable is arrogated for a
1695 special meaning. If you had templates before version 1.10 that
1696 happened to use a variable named C<$OUT>, you will have to change them
1697 to use some other variable or all sorts of strangeness will result.
1699 Between versions 0.1b and 1.00 the behavior of the \ metacharacter
1700 changed. In 0.1b, \\ was special everywhere, and the template
1701 processor always replaced it with a single backslash before passing
1702 the code to Perl for evaluation. The rule now is more complicated but
1703 probably more convenient. See the section on backslash processing,
1704 below, for a full discussion.
1706 =head2 Backslash Processing
1708 In C<Text::Template> beta versions, the backslash was special whenever
1709 it appeared before a brace or another backslash. That meant that
1710 while C<{"\n"}> did indeed generate a newline, C<{"\\"}> did not
1711 generate a backslash, because the code passed to Perl for evaluation
1712 was C<"\"> which is a syntax error. If you wanted a backslash, you
1713 would have had to write C<{"\\\\"}>.
1715 In C<Text::Template> versions 1.00 through 1.10, there was a bug:
1716 Backslash was special everywhere. In these versions, C<{"\n"}>
1717 generated the letter C<n>.
1719 The bug has been corrected in version 1.11, but I did not go back to
1720 exactly the old rule, because I did not like the idea of having to
1721 write C<{"\\\\"}> to get one backslash. The rule is now more
1722 complicated to remember, but probably easier to use. The rule is now:
1723 Backslashes are always passed to Perl unchanged I<unless> they occur
1724 as part of a sequence like C<\\\\\\{> or C<\\\\\\}>. In these
1725 contexts, they are special; C<\\> is replaced with C<\>, and C<\{> and
1726 C<\}> signal a literal brace.
1732 is I<not> evaluated, because the C<\> before the braces signals that
1733 they should be taken literally. The result in the output looks like this:
1738 This is a syntax error:
1742 because C<Text::Template> thinks that the code ends at the first C<}>,
1743 and then gets upset when it sees the second one. To make this work
1748 This passes C<"foo}"> to Perl for evaluation. Note there's no C<\> in
1749 the evaluated code. If you really want a C<\> in the evaluated code,
1754 This passes C<"foo\}"> to Perl for evaluation.
1756 Starting with C<Text::Template> version 1.20, backslash processing is
1757 disabled if you use the C<DELIMITERS> option to specify alternative
1760 =head2 A short note about C<$Text::Template::ERROR>
1762 In the past some people have fretted about `violating the package
1763 boundary' by examining a variable inside the C<Text::Template>
1764 package. Don't feel this way. C<$Text::Template::ERROR> is part of
1765 the published, official interface to this package. It is perfectly OK
1766 to inspect this variable. The interface is not going to change.
1768 If it really, really bothers you, you can import a function called
1769 C<TTerror> that returns the current value of the C<$ERROR> variable.
1772 use Text::Template 'TTerror';
1774 my $template = new Text::Template (SOURCE => $filename);
1775 unless ($template) {
1777 die "Couldn't make template: $err; aborting";
1780 I don't see what benefit this has over just doing this:
1784 my $template = new Text::Template (SOURCE => $filename)
1785 or die "Couldn't make template: $Text::Template::ERROR; aborting";
1787 But if it makes you happy to do it that way, go ahead.
1789 =head2 Sticky Widgets in Template Files
1791 The C<CGI> module provides functions for `sticky widgets', which are
1792 form input controls that retain their values from one page to the
1793 next. Sometimes people want to know how to include these widgets
1794 into their template output.
1796 It's totally straightforward. Just call the C<CGI> functions from
1797 inside the template:
1799 { $q->checkbox_group(NAME => 'toppings',
1802 VALUES => \@toppings,
1806 =head2 Automatic preprocessing of program fragments
1808 It may be useful to preprocess the program fragments before they are
1809 evaluated. See C<Text::Template::Preprocess> for more details.
1811 =head2 Automatic postprocessing of template hunks
1813 It may be useful to process hunks of output before they are appended to
1814 the result text. For this, subclass and replace the C<append_text_to_result>
1815 method. It is passed a list of pairs with these entries:
1817 handle - a filehandle to which to print the desired output
1818 out - a ref to a string to which to append, to use if handle is not given
1819 text - the text that will be appended
1820 type - where the text came from: TEXT for literal text, PROG for code
1824 Mark Jason Dominus, Plover Systems
1826 Please send questions and other remarks about this software to
1827 C<mjd-perl-template+@plover.com>
1829 You can join a very low-volume (E<lt>10 messages per year) mailing
1830 list for announcements about this package. Send an empty note to
1831 C<mjd-perl-template-request@plover.com> to join.
1833 For updates, visit C<http://www.plover.com/~mjd/perl/Template/>.
1837 This software is version 1.46. It may have bugs. Suggestions and bug
1838 reports are always welcome. Send them to
1839 C<mjd-perl-template+@plover.com>. (That is my address, not the address
1840 of the mailing list. The mailing list address is a secret.)
1844 Text::Template version 1.46
1845 Copyright 2013 Mark Jason Dominus
1847 This program is free software; you can redistribute it and/or
1848 modify it under the terms of the GNU General Public License as
1849 published by the Free Software Foundation; either version 2 of the
1850 License, or (at your option) any later version. You may also can
1851 redistribute it and/or modify it under the terms of the Perl
1854 This program is distributed in the hope that it will be useful,
1855 but WITHOUT ANY WARRANTY; without even the implied warranty of
1856 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1857 GNU General Public License for more details.
1859 You should have received copies of the GNU General Public License
1860 along with this program; if not, write to the Free Software
1861 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
1866 Many thanks to the following people for offering support,
1867 encouragement, advice, bug reports, and all the other good stuff.
1872 AntE<oacute>nio AragE<atilde>o /
1880 Itamar Almeida de Carvalho /
1889 Donald L. Greer Jr. /
1890 Michelangelo Grigni /
1915 Jennifer D. St Clair /
1917 Randal L. Schwartz /
1930 Lorenzo Valdettaro /
1946 for telling me how to do the C<Safe> support (I spent two years
1947 worrying about it, and then Jonathan pointed out that it was trivial.)
1949 =item Ranjit Bhatnagar
1951 for demanding less verbose fragments like they have in ASP, for
1952 helping me figure out the Right Thing, and, especially, for talking me
1953 out of adding any new syntax. These discussions resulted in the
1958 =head2 Bugs and Caveats
1960 C<my> variables in C<fill_in> are still susceptible to being clobbered
1961 by template evaluation. They all begin with C<fi_>, so avoid those
1962 names in your templates.
1964 The line number information will be wrong if the template's lines are
1965 not terminated by C<"\n">. You should let me know if this is a
1966 problem. If you do, I will fix it.
1968 The C<$OUT> variable has a special meaning in templates, so you cannot
1969 use it as if it were a regular variable.
1971 There are not quite enough tests in the test suite.