1# -*- perl -*- 2# Text::Template.pm 3# 4# Fill in `templates' 5# 6# Copyright 2013 M. J. Dominus. 7# You may copy and distribute this program under the 8# same terms as Perl itself. 9# If in doubt, write to mjd-perl-template+@plover.com for a license. 10# 11 12package Text::Template; 13$Text::Template::VERSION = '1.56'; 14# ABSTRACT: Expand template text with embedded Perl 15 16use strict; 17use warnings; 18 19require 5.008; 20 21use base 'Exporter'; 22 23our @EXPORT_OK = qw(fill_in_file fill_in_string TTerror); 24our $ERROR; 25 26my %GLOBAL_PREPEND = ('Text::Template' => ''); 27 28sub Version { 29 $Text::Template::VERSION; 30} 31 32sub _param { 33 my ($k, %h) = @_; 34 35 for my $kk ($k, "\u$k", "\U$k", "-$k", "-\u$k", "-\U$k") { 36 return $h{$kk} if exists $h{$kk}; 37 } 38 39 return undef; 40} 41 42sub always_prepend { 43 my $pack = shift; 44 45 my $old = $GLOBAL_PREPEND{$pack}; 46 47 $GLOBAL_PREPEND{$pack} = shift; 48 49 $old; 50} 51 52{ 53 my %LEGAL_TYPE; 54 55 BEGIN { 56 %LEGAL_TYPE = map { $_ => 1 } qw(FILE FILEHANDLE STRING ARRAY); 57 } 58 59 sub new { 60 my ($pack, %a) = @_; 61 62 my $stype = uc(_param('type', %a) || "FILE"); 63 my $source = _param('source', %a); 64 my $untaint = _param('untaint', %a); 65 my $prepend = _param('prepend', %a); 66 my $alt_delim = _param('delimiters', %a); 67 my $broken = _param('broken', %a); 68 my $encoding = _param('encoding', %a); 69 70 unless (defined $source) { 71 require Carp; 72 Carp::croak("Usage: $ {pack}::new(TYPE => ..., SOURCE => ...)"); 73 } 74 75 unless ($LEGAL_TYPE{$stype}) { 76 require Carp; 77 Carp::croak("Illegal value `$stype' for TYPE parameter"); 78 } 79 80 my $self = { 81 TYPE => $stype, 82 PREPEND => $prepend, 83 UNTAINT => $untaint, 84 BROKEN => $broken, 85 ENCODING => $encoding, 86 (defined $alt_delim ? (DELIM => $alt_delim) : ()) 87 }; 88 89 # Under 5.005_03, if any of $stype, $prepend, $untaint, or $broken 90 # are tainted, all the others become tainted too as a result of 91 # sharing the expression with them. We install $source separately 92 # to prevent it from acquiring a spurious taint. 93 $self->{SOURCE} = $source; 94 95 bless $self => $pack; 96 return unless $self->_acquire_data; 97 98 $self; 99 } 100} 101 102# Convert template objects of various types to type STRING, 103# in which the template data is embedded in the object itself. 104sub _acquire_data { 105 my $self = shift; 106 107 my $type = $self->{TYPE}; 108 109 if ($type eq 'STRING') { 110 # nothing necessary 111 } 112 elsif ($type eq 'FILE') { 113 my $data = _load_text($self->{SOURCE}); 114 unless (defined $data) { 115 116 # _load_text already set $ERROR 117 return undef; 118 } 119 120 if ($self->{UNTAINT} && _is_clean($self->{SOURCE})) { 121 _unconditionally_untaint($data); 122 } 123 124 if (defined $self->{ENCODING}) { 125 require Encode; 126 $data = Encode::decode($self->{ENCODING}, $data, &Encode::FB_CROAK); 127 } 128 129 $self->{TYPE} = 'STRING'; 130 $self->{FILENAME} = $self->{SOURCE}; 131 $self->{SOURCE} = $data; 132 } 133 elsif ($type eq 'ARRAY') { 134 $self->{TYPE} = 'STRING'; 135 $self->{SOURCE} = join '', @{ $self->{SOURCE} }; 136 } 137 elsif ($type eq 'FILEHANDLE') { 138 $self->{TYPE} = 'STRING'; 139 local $/; 140 my $fh = $self->{SOURCE}; 141 my $data = <$fh>; # Extra assignment avoids bug in Solaris perl5.00[45]. 142 if ($self->{UNTAINT}) { 143 _unconditionally_untaint($data); 144 } 145 $self->{SOURCE} = $data; 146 } 147 else { 148 # This should have been caught long ago, so it represents a 149 # drastic `can't-happen' sort of failure 150 my $pack = ref $self; 151 die "Can only acquire data for $pack objects of subtype STRING, but this is $type; aborting"; 152 } 153 154 $self->{DATA_ACQUIRED} = 1; 155} 156 157sub source { 158 my $self = shift; 159 160 $self->_acquire_data unless $self->{DATA_ACQUIRED}; 161 162 return $self->{SOURCE}; 163} 164 165sub set_source_data { 166 my ($self, $newdata, $type) = @_; 167 168 $self->{SOURCE} = $newdata; 169 $self->{DATA_ACQUIRED} = 1; 170 $self->{TYPE} = $type || 'STRING'; 171 172 1; 173} 174 175sub compile { 176 my $self = shift; 177 178 return 1 if $self->{TYPE} eq 'PREPARSED'; 179 180 return undef unless $self->_acquire_data; 181 182 unless ($self->{TYPE} eq 'STRING') { 183 my $pack = ref $self; 184 185 # This should have been caught long ago, so it represents a 186 # drastic `can't-happen' sort of failure 187 die "Can only compile $pack objects of subtype STRING, but this is $self->{TYPE}; aborting"; 188 } 189 190 my @tokens; 191 my $delim_pats = shift() || $self->{DELIM}; 192 193 my ($t_open, $t_close) = ('{', '}'); 194 my $DELIM; # Regex matches a delimiter if $delim_pats 195 196 if (defined $delim_pats) { 197 ($t_open, $t_close) = @$delim_pats; 198 $DELIM = "(?:(?:\Q$t_open\E)|(?:\Q$t_close\E))"; 199 @tokens = split /($DELIM|\n)/, $self->{SOURCE}; 200 } 201 else { 202 @tokens = split /(\\\\(?=\\*[{}])|\\[{}]|[{}\n])/, $self->{SOURCE}; 203 } 204 205 my $state = 'TEXT'; 206 my $depth = 0; 207 my $lineno = 1; 208 my @content; 209 my $cur_item = ''; 210 my $prog_start; 211 212 while (@tokens) { 213 my $t = shift @tokens; 214 215 next if $t eq ''; 216 217 if ($t eq $t_open) { # Brace or other opening delimiter 218 if ($depth == 0) { 219 push @content, [ $state, $cur_item, $lineno ] if $cur_item ne ''; 220 $cur_item = ''; 221 $state = 'PROG'; 222 $prog_start = $lineno; 223 } 224 else { 225 $cur_item .= $t; 226 } 227 $depth++; 228 } 229 elsif ($t eq $t_close) { # Brace or other closing delimiter 230 $depth--; 231 if ($depth < 0) { 232 $ERROR = "Unmatched close brace at line $lineno"; 233 return undef; 234 } 235 elsif ($depth == 0) { 236 push @content, [ $state, $cur_item, $prog_start ] if $cur_item ne ''; 237 $state = 'TEXT'; 238 $cur_item = ''; 239 } 240 else { 241 $cur_item .= $t; 242 } 243 } 244 elsif (!$delim_pats && $t eq '\\\\') { # precedes \\\..\\\{ or \\\..\\\} 245 $cur_item .= '\\'; 246 } 247 elsif (!$delim_pats && $t =~ /^\\([{}])$/) { # Escaped (literal) brace? 248 $cur_item .= $1; 249 } 250 elsif ($t eq "\n") { # Newline 251 $lineno++; 252 $cur_item .= $t; 253 } 254 else { # Anything else 255 $cur_item .= $t; 256 } 257 } 258 259 if ($state eq 'PROG') { 260 $ERROR = "End of data inside program text that began at line $prog_start"; 261 return undef; 262 } 263 elsif ($state eq 'TEXT') { 264 push @content, [ $state, $cur_item, $lineno ] if $cur_item ne ''; 265 } 266 else { 267 die "Can't happen error #1"; 268 } 269 270 $self->{TYPE} = 'PREPARSED'; 271 $self->{SOURCE} = \@content; 272 273 1; 274} 275 276sub prepend_text { 277 my $self = shift; 278 279 my $t = $self->{PREPEND}; 280 281 unless (defined $t) { 282 $t = $GLOBAL_PREPEND{ ref $self }; 283 unless (defined $t) { 284 $t = $GLOBAL_PREPEND{'Text::Template'}; 285 } 286 } 287 288 $self->{PREPEND} = $_[1] if $#_ >= 1; 289 290 return $t; 291} 292 293sub fill_in { 294 my ($fi_self, %fi_a) = @_; 295 296 unless ($fi_self->{TYPE} eq 'PREPARSED') { 297 my $delims = _param('delimiters', %fi_a); 298 my @delim_arg = (defined $delims ? ($delims) : ()); 299 $fi_self->compile(@delim_arg) 300 or return undef; 301 } 302 303 my $fi_varhash = _param('hash', %fi_a); 304 my $fi_package = _param('package', %fi_a); 305 my $fi_broken = _param('broken', %fi_a) || $fi_self->{BROKEN} || \&_default_broken; 306 my $fi_broken_arg = _param('broken_arg', %fi_a) || []; 307 my $fi_safe = _param('safe', %fi_a); 308 my $fi_ofh = _param('output', %fi_a); 309 my $fi_filename = _param('filename', %fi_a) || $fi_self->{FILENAME} || 'template'; 310 my $fi_strict = _param('strict', %fi_a); 311 my $fi_prepend = _param('prepend', %fi_a); 312 313 my $fi_eval_package; 314 my $fi_scrub_package = 0; 315 316 unless (defined $fi_prepend) { 317 $fi_prepend = $fi_self->prepend_text; 318 } 319 320 if (defined $fi_safe) { 321 $fi_eval_package = 'main'; 322 } 323 elsif (defined $fi_package) { 324 $fi_eval_package = $fi_package; 325 } 326 elsif (defined $fi_varhash) { 327 $fi_eval_package = _gensym(); 328 $fi_scrub_package = 1; 329 } 330 else { 331 $fi_eval_package = caller; 332 } 333 334 my @fi_varlist; 335 my $fi_install_package; 336 337 if (defined $fi_varhash) { 338 if (defined $fi_package) { 339 $fi_install_package = $fi_package; 340 } 341 elsif (defined $fi_safe) { 342 $fi_install_package = $fi_safe->root; 343 } 344 else { 345 $fi_install_package = $fi_eval_package; # The gensymmed one 346 } 347 @fi_varlist = _install_hash($fi_varhash => $fi_install_package); 348 if ($fi_strict) { 349 $fi_prepend = "use vars qw(@fi_varlist);$fi_prepend" if @fi_varlist; 350 $fi_prepend = "use strict;$fi_prepend"; 351 } 352 } 353 354 if (defined $fi_package && defined $fi_safe) { 355 no strict 'refs'; 356 357 # Big fat magic here: Fix it so that the user-specified package 358 # is the default one available in the safe compartment. 359 *{ $fi_safe->root . '::' } = \%{ $fi_package . '::' }; # LOD 360 } 361 362 my $fi_r = ''; 363 my $fi_item; 364 foreach $fi_item (@{ $fi_self->{SOURCE} }) { 365 my ($fi_type, $fi_text, $fi_lineno) = @$fi_item; 366 if ($fi_type eq 'TEXT') { 367 $fi_self->append_text_to_output( 368 text => $fi_text, 369 handle => $fi_ofh, 370 out => \$fi_r, 371 type => $fi_type,); 372 } 373 elsif ($fi_type eq 'PROG') { 374 no strict; 375 376 my $fi_lcomment = "#line $fi_lineno $fi_filename"; 377 my $fi_progtext = "package $fi_eval_package; $fi_prepend;\n$fi_lcomment\n$fi_text;\n;"; 378 my $fi_res; 379 my $fi_eval_err = ''; 380 381 if ($fi_safe) { 382 no strict; 383 no warnings; 384 385 $fi_safe->reval(q{undef $OUT}); 386 $fi_res = $fi_safe->reval($fi_progtext); 387 $fi_eval_err = $@; 388 my $OUT = $fi_safe->reval('$OUT'); 389 $fi_res = $OUT if defined $OUT; 390 } 391 else { 392 no strict; 393 no warnings; 394 395 my $OUT; 396 $fi_res = eval $fi_progtext; 397 $fi_eval_err = $@; 398 $fi_res = $OUT if defined $OUT; 399 } 400 401 # If the value of the filled-in text really was undef, 402 # change it to an explicit empty string to avoid undefined 403 # value warnings later. 404 $fi_res = '' unless defined $fi_res; 405 406 if ($fi_eval_err) { 407 $fi_res = $fi_broken->( 408 text => $fi_text, 409 error => $fi_eval_err, 410 lineno => $fi_lineno, 411 arg => $fi_broken_arg,); 412 if (defined $fi_res) { 413 $fi_self->append_text_to_output( 414 text => $fi_res, 415 handle => $fi_ofh, 416 out => \$fi_r, 417 type => $fi_type,); 418 } 419 else { 420 return $fi_r; # Undefined means abort processing 421 } 422 } 423 else { 424 $fi_self->append_text_to_output( 425 text => $fi_res, 426 handle => $fi_ofh, 427 out => \$fi_r, 428 type => $fi_type,); 429 } 430 } 431 else { 432 die "Can't happen error #2"; 433 } 434 } 435 436 _scrubpkg($fi_eval_package) if $fi_scrub_package; 437 438 defined $fi_ofh ? 1 : $fi_r; 439} 440 441sub append_text_to_output { 442 my ($self, %arg) = @_; 443 444 if (defined $arg{handle}) { 445 print { $arg{handle} } $arg{text}; 446 } 447 else { 448 ${ $arg{out} } .= $arg{text}; 449 } 450 451 return; 452} 453 454sub fill_this_in { 455 my ($pack, $text) = splice @_, 0, 2; 456 457 my $templ = $pack->new(TYPE => 'STRING', SOURCE => $text, @_) 458 or return undef; 459 460 $templ->compile or return undef; 461 462 my $result = $templ->fill_in(@_); 463 464 $result; 465} 466 467sub fill_in_string { 468 my $string = shift; 469 470 my $package = _param('package', @_); 471 472 push @_, 'package' => scalar(caller) unless defined $package; 473 474 Text::Template->fill_this_in($string, @_); 475} 476 477sub fill_in_file { 478 my $fn = shift; 479 my $templ = Text::Template->new(TYPE => 'FILE', SOURCE => $fn, @_) or return undef; 480 481 $templ->compile or return undef; 482 483 my $text = $templ->fill_in(@_); 484 485 $text; 486} 487 488sub _default_broken { 489 my %a = @_; 490 491 my $prog_text = $a{text}; 492 my $err = $a{error}; 493 my $lineno = $a{lineno}; 494 495 chomp $err; 496 497 # $err =~ s/\s+at .*//s; 498 "Program fragment delivered error ``$err''"; 499} 500 501sub _load_text { 502 my $fn = shift; 503 504 open my $fh, '<', $fn or do { 505 $ERROR = "Couldn't open file $fn: $!"; 506 return undef; 507 }; 508 509 local $/; 510 511 <$fh>; 512} 513 514sub _is_clean { 515 my $z; 516 517 eval { ($z = join('', @_)), eval '#' . substr($z, 0, 0); 1 } # LOD 518} 519 520sub _unconditionally_untaint { 521 for (@_) { 522 ($_) = /(.*)/s; 523 } 524} 525 526{ 527 my $seqno = 0; 528 529 sub _gensym { 530 __PACKAGE__ . '::GEN' . $seqno++; 531 } 532 533 sub _scrubpkg { 534 my $s = shift; 535 536 $s =~ s/^Text::Template:://; 537 538 no strict 'refs'; 539 540 my $hash = $Text::Template::{ $s . "::" }; 541 542 foreach my $key (keys %$hash) { 543 undef $hash->{$key}; 544 } 545 546 %$hash = (); 547 548 delete $Text::Template::{ $s . "::" }; 549 } 550} 551 552# Given a hashful of variables (or a list of such hashes) 553# install the variables into the specified package, 554# overwriting whatever variables were there before. 555sub _install_hash { 556 my $hashlist = shift; 557 my $dest = shift; 558 559 if (UNIVERSAL::isa($hashlist, 'HASH')) { 560 $hashlist = [$hashlist]; 561 } 562 563 my @varlist; 564 565 for my $hash (@$hashlist) { 566 for my $name (keys %$hash) { 567 my $val = $hash->{$name}; 568 569 no strict 'refs'; 570 no warnings 'redefine'; 571 572 local *SYM = *{"$ {dest}::$name"}; 573 574 if (!defined $val) { 575 delete ${"$ {dest}::"}{$name}; 576 my $match = qr/^.\Q$name\E$/; 577 @varlist = grep { $_ !~ $match } @varlist; 578 } 579 elsif (ref $val) { 580 *SYM = $val; 581 push @varlist, do { 582 if (UNIVERSAL::isa($val, 'ARRAY')) { '@' } 583 elsif (UNIVERSAL::isa($val, 'HASH')) { '%' } 584 else { '$' } 585 } 586 . $name; 587 } 588 else { 589 *SYM = \$val; 590 push @varlist, '$' . $name; 591 } 592 } 593 } 594 595 @varlist; 596} 597 598sub TTerror { $ERROR } 599 6001; 601 602__END__ 603 604=pod 605 606=encoding UTF-8 607 608=head1 NAME 609 610Text::Template - Expand template text with embedded Perl 611 612=head1 VERSION 613 614version 1.56 615 616=head1 SYNOPSIS 617 618 use Text::Template; 619 620 621 $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'filename.tmpl'); 622 $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] ); 623 $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh ); 624 $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' ); 625 $template = Text::Template->new(PREPEND => q{use strict;}, ...); 626 627 # Use a different template file syntax: 628 $template = Text::Template->new(DELIMITERS => [$open, $close], ...); 629 630 $recipient = 'King'; 631 $text = $template->fill_in(); # Replaces `{$recipient}' with `King' 632 print $text; 633 634 $T::recipient = 'Josh'; 635 $text = $template->fill_in(PACKAGE => T); 636 637 # Pass many variables explicitly 638 $hash = { recipient => 'Abed-Nego', 639 friends => [ 'me', 'you' ], 640 enemies => { loathsome => 'Saruman', 641 fearsome => 'Sauron' }, 642 }; 643 $text = $template->fill_in(HASH => $hash, ...); 644 # $recipient is Abed-Nego, 645 # @friends is ( 'me', 'you' ), 646 # %enemies is ( loathsome => ..., fearsome => ... ) 647 648 649 # Call &callback in case of programming errors in template 650 $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...); 651 652 # Evaluate program fragments in Safe compartment with restricted permissions 653 $text = $template->fill_in(SAFE => $compartment, ...); 654 655 # Print result text instead of returning it 656 $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...); 657 658 # Parse template with different template file syntax: 659 $text = $template->fill_in(DELIMITERS => [$open, $close], ...); 660 # Note that this is *faster* than using the default delimiters 661 662 # Prepend specified perl code to each fragment before evaluating: 663 $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...); 664 665 use Text::Template 'fill_in_string'; 666 $text = fill_in_string( <<EOM, PACKAGE => 'T', ...); 667 Dear {$recipient}, 668 Pay me at once. 669 Love, 670 G.V. 671 EOM 672 673 use Text::Template 'fill_in_file'; 674 $text = fill_in_file($filename, ...); 675 676 # All templates will always have `use strict vars' attached to all fragments 677 Text::Template->always_prepend(q{use strict 'vars';}); 678 679=head1 DESCRIPTION 680 681This is a library for generating form letters, building HTML pages, or 682filling in templates generally. A `template' is a piece of text that 683has little Perl programs embedded in it here and there. When you 684`fill in' a template, you evaluate the little programs and replace 685them with their values. 686 687You can store a template in a file outside your program. People can 688modify the template without modifying the program. You can separate 689the formatting details from the main code, and put the formatting 690parts of the program into the template. That prevents code bloat and 691encourages functional separation. 692 693=head2 Example 694 695Here's an example of a template, which we'll suppose is stored in the 696file C<formletter.tmpl>: 697 698 Dear {$title} {$lastname}, 699 700 It has come to our attention that you are delinquent in your 701 {$monthname[$last_paid_month]} payment. Please remit 702 ${sprintf("%.2f", $amount)} immediately, or your patellae may 703 be needlessly endangered. 704 705 Love, 706 707 Mark "Vizopteryx" Dominus 708 709The result of filling in this template is a string, which might look 710something like this: 711 712 Dear Mr. Smith, 713 714 It has come to our attention that you are delinquent in your 715 February payment. Please remit 716 $392.12 immediately, or your patellae may 717 be needlessly endangered. 718 719 720 Love, 721 722 Mark "Vizopteryx" Dominus 723 724Here is a complete program that transforms the example 725template into the example result, and prints it out: 726 727 use Text::Template; 728 729 my $template = Text::Template->new(SOURCE => 'formletter.tmpl') 730 or die "Couldn't construct template: $Text::Template::ERROR"; 731 732 my @monthname = qw(January February March April May June 733 July August September October November December); 734 my %vars = (title => 'Mr.', 735 firstname => 'John', 736 lastname => 'Smith', 737 last_paid_month => 1, # February 738 amount => 392.12, 739 monthname => \@monthname); 740 741 my $result = $template->fill_in(HASH => \%vars); 742 743 if (defined $result) { print $result } 744 else { die "Couldn't fill in template: $Text::Template::ERROR" } 745 746=head2 Philosophy 747 748When people make a template module like this one, they almost always 749start by inventing a special syntax for substitutions. For example, 750they build it so that a string like C<%%VAR%%> is replaced with the 751value of C<$VAR>. Then they realize the need extra formatting, so 752they put in some special syntax for formatting. Then they need a 753loop, so they invent a loop syntax. Pretty soon they have a new 754little template language. 755 756This approach has two problems: First, their little language is 757crippled. If you need to do something the author hasn't thought of, 758you lose. Second: Who wants to learn another language? You already 759know Perl, so why not use it? 760 761C<Text::Template> templates are programmed in I<Perl>. You embed Perl 762code in your template, with C<{> at the beginning and C<}> at the end. 763If you want a variable interpolated, you write it the way you would in 764Perl. If you need to make a loop, you can use any of the Perl loop 765constructions. All the Perl built-in functions are available. 766 767=head1 Details 768 769=head2 Template Parsing 770 771The C<Text::Template> module scans the template source. An open brace 772C<{> begins a program fragment, which continues until the matching 773close brace C<}>. When the template is filled in, the program 774fragments are evaluated, and each one is replaced with the resulting 775value to yield the text that is returned. 776 777A backslash C<\> in front of a brace (or another backslash that is in 778front of a brace) escapes its special meaning. The result of filling 779out this template: 780 781 \{ The sum of 1 and 2 is {1+2} \} 782 783is 784 785 { The sum of 1 and 2 is 3 } 786 787If you have an unmatched brace, C<Text::Template> will return a 788failure code and a warning about where the problem is. Backslashes 789that do not precede a brace are passed through unchanged. If you have 790a template like this: 791 792 { "String that ends in a newline.\n" } 793 794The backslash inside the string is passed through to Perl unchanged, 795so the C<\n> really does turn into a newline. See the note at the end 796for details about the way backslashes work. Backslash processing is 797I<not> done when you specify alternative delimiters with the 798C<DELIMITERS> option. (See L<"Alternative Delimiters">, below.) 799 800Each program fragment should be a sequence of Perl statements, which 801are evaluated the usual way. The result of the last statement 802executed will be evaluated in scalar context; the result of this 803statement is a string, which is interpolated into the template in 804place of the program fragment itself. 805 806The fragments are evaluated in order, and side effects from earlier 807fragments will persist into later fragments: 808 809 {$x = @things; ''}The Lord High Chamberlain has gotten {$x} 810 things for me this year. 811 { $diff = $x - 17; 812 $more = 'more' 813 if ($diff == 0) { 814 $diff = 'no'; 815 } elsif ($diff < 0) { 816 $more = 'fewer'; 817 } 818 ''; 819 } 820 That is {$diff} {$more} than he gave me last year. 821 822The value of C<$x> set in the first line will persist into the next 823fragment that begins on the third line, and the values of C<$diff> and 824C<$more> set in the second fragment will persist and be interpolated 825into the last line. The output will look something like this: 826 827 The Lord High Chamberlain has gotten 42 828 things for me this year. 829 830 That is 25 more than he gave me last year. 831 832That is all the syntax there is. 833 834=head2 The C<$OUT> variable 835 836There is one special trick you can play in a template. Here is the 837motivation for it: Suppose you are going to pass an array, C<@items>, 838into the template, and you want the template to generate a bulleted 839list with a header, like this: 840 841 Here is a list of the things I have got for you since 1907: 842 * Ivory 843 * Apes 844 * Peacocks 845 * ... 846 847One way to do it is with a template like this: 848 849 Here is a list of the things I have got for you since 1907: 850 { my $blist = ''; 851 foreach $i (@items) { 852 $blist .= qq{ * $i\n}; 853 } 854 $blist; 855 } 856 857Here we construct the list in a variable called C<$blist>, which we 858return at the end. This is a little cumbersome. There is a shortcut. 859 860Inside of templates, there is a special variable called C<$OUT>. 861Anything you append to this variable will appear in the output of the 862template. Also, if you use C<$OUT> in a program fragment, the normal 863behavior, of replacing the fragment with its return value, is 864disabled; instead the fragment is replaced with the value of C<$OUT>. 865This means that you can write the template above like this: 866 867 Here is a list of the things I have got for you since 1907: 868 { foreach $i (@items) { 869 $OUT .= " * $i\n"; 870 } 871 } 872 873C<$OUT> is reinitialized to the empty string at the start of each 874program fragment. It is private to C<Text::Template>, so 875you can't use a variable named C<$OUT> in your template without 876invoking the special behavior. 877 878=head2 General Remarks 879 880All C<Text::Template> functions return C<undef> on failure, and set the 881variable C<$Text::Template::ERROR> to contain an explanation of what 882went wrong. For example, if you try to create a template from a file 883that does not exist, C<$Text::Template::ERROR> will contain something like: 884 885 Couldn't open file xyz.tmpl: No such file or directory 886 887=head2 C<new> 888 889 $template = Text::Template->new( TYPE => ..., SOURCE => ... ); 890 891This creates and returns a new template object. C<new> returns 892C<undef> and sets C<$Text::Template::ERROR> if it can't create the 893template object. C<SOURCE> says where the template source code will 894come from. C<TYPE> says what kind of object the source is. 895 896The most common type of source is a file: 897 898 Text::Template->new( TYPE => 'FILE', SOURCE => $filename ); 899 900This reads the template from the specified file. The filename is 901opened with the Perl C<open> command, so it can be a pipe or anything 902else that makes sense with C<open>. 903 904The C<TYPE> can also be C<STRING>, in which case the C<SOURCE> should 905be a string: 906 907 Text::Template->new( TYPE => 'STRING', 908 SOURCE => "This is the actual template!" ); 909 910The C<TYPE> can be C<ARRAY>, in which case the source should be a 911reference to an array of strings. The concatenation of these strings 912is the template: 913 914 Text::Template->new( TYPE => 'ARRAY', 915 SOURCE => [ "This is ", "the actual", 916 " template!", 917 ] 918 ); 919 920The C<TYPE> can be FILEHANDLE, in which case the source should be an 921open filehandle (such as you got from the C<FileHandle> or C<IO::*> 922packages, or a glob, or a reference to a glob). In this case 923C<Text::Template> will read the text from the filehandle up to 924end-of-file, and that text is the template: 925 926 # Read template source code from STDIN: 927 Text::Template->new ( TYPE => 'FILEHANDLE', 928 SOURCE => \*STDIN ); 929 930If you omit the C<TYPE> attribute, it's taken to be C<FILE>. 931C<SOURCE> is required. If you omit it, the program will abort. 932 933The words C<TYPE> and C<SOURCE> can be spelled any of the following ways: 934 935 TYPE SOURCE 936 Type Source 937 type source 938 -TYPE -SOURCE 939 -Type -Source 940 -type -source 941 942Pick a style you like and stick with it. 943 944=over 4 945 946=item C<DELIMITERS> 947 948You may also add a C<DELIMITERS> option. If this option is present, 949its value should be a reference to an array of two strings. The first 950string is the string that signals the beginning of each program 951fragment, and the second string is the string that signals the end of 952each program fragment. See L<"Alternative Delimiters">, below. 953 954=item C<ENCODING> 955 956You may also add a C<ENCODING> option. If this option is present, and the 957C<SOURCE> is a C<FILE>, then the data will be decoded from the given encoding 958using the L<Encode> module. You can use any encoding that L<Encode> recognizes. 959E.g.: 960 961 Text::Template->new( 962 TYPE => 'FILE', 963 ENCODING => 'UTF-8', 964 SOURCE => 'xyz.tmpl'); 965 966=item C<UNTAINT> 967 968If your program is running in taint mode, you may have problems if 969your templates are stored in files. Data read from files is 970considered 'untrustworthy', and taint mode will not allow you to 971evaluate the Perl code in the file. (It is afraid that a malicious 972person might have tampered with the file.) 973 974In some environments, however, local files are trustworthy. You can 975tell C<Text::Template> that a certain file is trustworthy by supplying 976C<UNTAINT =E<gt> 1> in the call to C<new>. This will tell 977C<Text::Template> to disable taint checks on template code that has 978come from a file, as long as the filename itself is considered 979trustworthy. It will also disable taint checks on template code that 980comes from a filehandle. When used with C<TYPE =E<gt> 'string'> or C<TYPE 981=E<gt> 'array'>, it has no effect. 982 983See L<perlsec> for more complete information about tainting. 984 985Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph Baehr 986for help with this feature. 987 988=item C<PREPEND> 989 990This option is passed along to the C<fill_in> call unless it is 991overridden in the arguments to C<fill_in>. See L<C<PREPEND> feature 992and using C<strict> in templates> below. 993 994=item C<BROKEN> 995 996This option is passed along to the C<fill_in> call unless it is 997overridden in the arguments to C<fill_in>. See L<C<BROKEN>> below. 998 999=back 1000 1001=head2 C<compile> 1002 1003 $template->compile() 1004 1005Loads all the template text from the template's source, parses and 1006compiles it. If successful, returns true; otherwise returns false and 1007sets C<$Text::Template::ERROR>. If the template is already compiled, 1008it returns true and does nothing. 1009 1010You don't usually need to invoke this function, because C<fill_in> 1011(see below) compiles the template if it isn't compiled already. 1012 1013If there is an argument to this function, it must be a reference to an 1014array containing alternative delimiter strings. See C<"Alternative 1015Delimiters">, below. 1016 1017=head2 C<fill_in> 1018 1019 $template->fill_in(OPTIONS); 1020 1021Fills in a template. Returns the resulting text if successful. 1022Otherwise, returns C<undef> and sets C<$Text::Template::ERROR>. 1023 1024The I<OPTIONS> are a hash, or a list of key-value pairs. You can 1025write the key names in any of the six usual styles as above; this 1026means that where this manual says C<PACKAGE> (for example) you can 1027actually use any of 1028 1029 PACKAGE Package package -PACKAGE -Package -package 1030 1031Pick a style you like and stick with it. The all-lowercase versions 1032may yield spurious warnings about 1033 1034 Ambiguous use of package => resolved to "package" 1035 1036so you might like to avoid them and use the capitalized versions. 1037 1038At present, there are eight legal options: C<PACKAGE>, C<BROKEN>, 1039C<BROKEN_ARG>, C<FILENAME>, C<SAFE>, C<HASH>, C<OUTPUT>, and C<DELIMITERS>. 1040 1041=over 4 1042 1043=item C<PACKAGE> 1044 1045C<PACKAGE> specifies the name of a package in which the program 1046fragments should be evaluated. The default is to use the package from 1047which C<fill_in> was called. For example, consider this template: 1048 1049 The value of the variable x is {$x}. 1050 1051If you use C<$template-E<gt>fill_in(PACKAGE =E<gt> 'R')> , then the C<$x> in 1052the template is actually replaced with the value of C<$R::x>. If you 1053omit the C<PACKAGE> option, C<$x> will be replaced with the value of 1054the C<$x> variable in the package that actually called C<fill_in>. 1055 1056You should almost always use C<PACKAGE>. If you don't, and your 1057template makes changes to variables, those changes will be propagated 1058back into the main program. Evaluating the template in a private 1059package helps prevent this. The template can still modify variables 1060in your program if it wants to, but it will have to do so explicitly. 1061See the section at the end on `Security'. 1062 1063Here's an example of using C<PACKAGE>: 1064 1065 Your Royal Highness, 1066 1067 Enclosed please find a list of things I have gotten 1068 for you since 1907: 1069 1070 { foreach $item (@items) { 1071 $item_no++; 1072 $OUT .= " $item_no. \u$item\n"; 1073 } 1074 } 1075 1076 Signed, 1077 Lord High Chamberlain 1078 1079We want to pass in an array which will be assigned to the array 1080C<@items>. Here's how to do that: 1081 1082 @items = ('ivory', 'apes', 'peacocks', ); 1083 $template->fill_in(); 1084 1085This is not very safe. The reason this isn't as safe is that if you 1086had a variable named C<$item_no> in scope in your program at the point 1087you called C<fill_in>, its value would be clobbered by the act of 1088filling out the template. The problem is the same as if you had 1089written a subroutine that used those variables in the same way that 1090the template does. (C<$OUT> is special in templates and is always 1091safe.) 1092 1093One solution to this is to make the C<$item_no> variable private to the 1094template by declaring it with C<my>. If the template does this, you 1095are safe. 1096 1097But if you use the C<PACKAGE> option, you will probably be safe even 1098if the template does I<not> declare its variables with C<my>: 1099 1100 @Q::items = ('ivory', 'apes', 'peacocks', ); 1101 $template->fill_in(PACKAGE => 'Q'); 1102 1103In this case the template will clobber the variable C<$Q::item_no>, 1104which is not related to the one your program was using. 1105 1106Templates cannot affect variables in the main program that are 1107declared with C<my>, unless you give the template references to those 1108variables. 1109 1110=item C<HASH> 1111 1112You may not want to put the template variables into a package. 1113Packages can be hard to manage: You can't copy them, for example. 1114C<HASH> provides an alternative. 1115 1116The value for C<HASH> should be a reference to a hash that maps 1117variable names to values. For example, 1118 1119 $template->fill_in( 1120 HASH => { 1121 recipient => "The King", 1122 items => ['gold', 'frankincense', 'myrrh'], 1123 object => \$self, 1124 } 1125 ); 1126 1127will fill out the template and use C<"The King"> as the value of 1128C<$recipient> and the list of items as the value of C<@items>. Note 1129that we pass an array reference, but inside the template it appears as 1130an array. In general, anything other than a simple string or number 1131should be passed by reference. 1132 1133We also want to pass an object, which is in C<$self>; note that we 1134pass a reference to the object, C<\$self> instead. Since we've passed 1135a reference to a scalar, inside the template the object appears as 1136C<$object>. 1137 1138The full details of how it works are a little involved, so you might 1139want to skip to the next section. 1140 1141Suppose the key in the hash is I<key> and the value is I<value>. 1142 1143=over 4 1144 1145=item * 1146 1147If the I<value> is C<undef>, then any variables named C<$key>, 1148C<@key>, C<%key>, etc., are undefined. 1149 1150=item * 1151 1152If the I<value> is a string or a number, then C<$key> is set to that 1153value in the template. 1154 1155=item * 1156 1157For anything else, you must pass a reference. 1158 1159If the I<value> is a reference to an array, then C<@key> is set to 1160that array. If the I<value> is a reference to a hash, then C<%key> is 1161set to that hash. Similarly if I<value> is any other kind of 1162reference. This means that 1163 1164 var => "foo" 1165 1166and 1167 1168 var => \"foo" 1169 1170have almost exactly the same effect. (The difference is that in the 1171former case, the value is copied, and in the latter case it is 1172aliased.) 1173 1174=item * 1175 1176In particular, if you want the template to get an object or any kind, 1177you must pass a reference to it: 1178 1179 $template->fill_in(HASH => { database_handle => \$dbh, ... }); 1180 1181If you do this, the template will have a variable C<$database_handle> 1182which is the database handle object. If you leave out the C<\>, the 1183template will have a hash C<%database_handle>, which exposes the 1184internal structure of the database handle object; you don't want that. 1185 1186=back 1187 1188Normally, the way this works is by allocating a private package, 1189loading all the variables into the package, and then filling out the 1190template as if you had specified that package. A new package is 1191allocated each time. However, if you I<also> use the C<PACKAGE> 1192option, C<Text::Template> loads the variables into the package you 1193specified, and they stay there after the call returns. Subsequent 1194calls to C<fill_in> that use the same package will pick up the values 1195you loaded in. 1196 1197If the argument of C<HASH> is a reference to an array instead of a 1198reference to a hash, then the array should contain a list of hashes 1199whose contents are loaded into the template package one after the 1200other. You can use this feature if you want to combine several sets 1201of variables. For example, one set of variables might be the defaults 1202for a fill-in form, and the second set might be the user inputs, which 1203override the defaults when they are present: 1204 1205 $template->fill_in(HASH => [\%defaults, \%user_input]); 1206 1207You can also use this to set two variables with the same name: 1208 1209 $template->fill_in( 1210 HASH => [ 1211 { v => "The King" }, 1212 { v => [1,2,3] } 1213 ] 1214 ); 1215 1216This sets C<$v> to C<"The King"> and C<@v> to C<(1,2,3)>. 1217 1218=item C<BROKEN> 1219 1220If any of the program fragments fails to compile or aborts for any 1221reason, and you have set the C<BROKEN> option to a function reference, 1222C<Text::Template> will invoke the function. This function is called 1223the I<C<BROKEN> function>. The C<BROKEN> function will tell 1224C<Text::Template> what to do next. 1225 1226If the C<BROKEN> function returns C<undef>, C<Text::Template> will 1227immediately abort processing the template and return the text that it 1228has accumulated so far. If your function does this, it should set a 1229flag that you can examine after C<fill_in> returns so that you can 1230tell whether there was a premature return or not. 1231 1232If the C<BROKEN> function returns any other value, that value will be 1233interpolated into the template as if that value had been the return 1234value of the program fragment to begin with. For example, if the 1235C<BROKEN> function returns an error string, the error string will be 1236interpolated into the output of the template in place of the program 1237fragment that cased the error. 1238 1239If you don't specify a C<BROKEN> function, C<Text::Template> supplies 1240a default one that returns something like 1241 1242 Program fragment delivered error ``Illegal division by 0 at 1243 template line 37'' 1244 1245(Note that the format of this message has changed slightly since 1246version 1.31.) The return value of the C<BROKEN> function is 1247interpolated into the template at the place the error occurred, so 1248that this template: 1249 1250 (3+4)*5 = { 3+4)*5 } 1251 1252yields this result: 1253 1254 (3+4)*5 = Program fragment delivered error ``syntax error at template line 1'' 1255 1256If you specify a value for the C<BROKEN> attribute, it should be a 1257reference to a function that C<fill_in> can call instead of the 1258default function. 1259 1260C<fill_in> will pass a hash to the C<broken> function. 1261The hash will have at least these three members: 1262 1263=over 4 1264 1265=item C<text> 1266 1267The source code of the program fragment that failed 1268 1269=item C<error> 1270 1271The text of the error message (C<$@>) generated by eval. 1272 1273The text has been modified to omit the trailing newline and to include 1274the name of the template file (if there was one). The line number 1275counts from the beginning of the template, not from the beginning of 1276the failed program fragment. 1277 1278=item C<lineno> 1279 1280The line number of the template at which the program fragment began. 1281 1282=back 1283 1284There may also be an C<arg> member. See C<BROKEN_ARG>, below 1285 1286=item C<BROKEN_ARG> 1287 1288If you supply the C<BROKEN_ARG> option to C<fill_in>, the value of the 1289option is passed to the C<BROKEN> function whenever it is called. The 1290default C<BROKEN> function ignores the C<BROKEN_ARG>, but you can 1291write a custom C<BROKEN> function that uses the C<BROKEN_ARG> to get 1292more information about what went wrong. 1293 1294The C<BROKEN> function could also use the C<BROKEN_ARG> as a reference 1295to store an error message or some other information that it wants to 1296communicate back to the caller. For example: 1297 1298 $error = ''; 1299 1300 sub my_broken { 1301 my %args = @_; 1302 my $err_ref = $args{arg}; 1303 ... 1304 $$err_ref = "Some error message"; 1305 return undef; 1306 } 1307 1308 $template->fill_in( 1309 BROKEN => \&my_broken, 1310 BROKEN_ARG => \$error 1311 ); 1312 1313 if ($error) { 1314 die "It didn't work: $error"; 1315 } 1316 1317If one of the program fragments in the template fails, it will call 1318the C<BROKEN> function, C<my_broken>, and pass it the C<BROKEN_ARG>, 1319which is a reference to C<$error>. C<my_broken> can store an error 1320message into C<$error> this way. Then the function that called 1321C<fill_in> can see if C<my_broken> has left an error message for it 1322to find, and proceed accordingly. 1323 1324=item C<FILENAME> 1325 1326If you give C<fill_in> a C<FILENAME> option, then this is the file name that 1327you loaded the template source from. This only affects the error message that 1328is given for template errors. If you loaded the template from C<foo.txt> for 1329example, and pass C<foo.txt> as the C<FILENAME> parameter, errors will look 1330like C<... at foo.txt line N> rather than C<... at template line N>. 1331 1332Note that this does NOT have anything to do with loading a template from the 1333given filename. See C<fill_in_file()> for that. 1334 1335For example: 1336 1337 my $template = Text::Template->new( 1338 TYPE => 'string', 1339 SOURCE => 'The value is {1/0}'); 1340 1341 $template->fill_in(FILENAME => 'foo.txt') or die $Text::Template::ERROR; 1342 1343will die with an error that contains 1344 1345 Illegal division by zero at at foo.txt line 1 1346 1347=item C<SAFE> 1348 1349If you give C<fill_in> a C<SAFE> option, its value should be a safe 1350compartment object from the C<Safe> package. All evaluation of 1351program fragments will be performed in this compartment. See L<Safe> 1352for full details about such compartments and how to restrict the 1353operations that can be performed in them. 1354 1355If you use the C<PACKAGE> option with C<SAFE>, the package you specify 1356will be placed into the safe compartment and evaluation will take 1357place in that package as usual. 1358 1359If not, C<SAFE> operation is a little different from the default. 1360Usually, if you don't specify a package, evaluation of program 1361fragments occurs in the package from which the template was invoked. 1362But in C<SAFE> mode the evaluation occurs inside the safe compartment 1363and cannot affect the calling package. Normally, if you use C<HASH> 1364without C<PACKAGE>, the hash variables are imported into a private, 1365one-use-only package. But if you use C<HASH> and C<SAFE> together 1366without C<PACKAGE>, the hash variables will just be loaded into the 1367root namespace of the C<Safe> compartment. 1368 1369=item C<OUTPUT> 1370 1371If your template is going to generate a lot of text that you are just 1372going to print out again anyway, you can save memory by having 1373C<Text::Template> print out the text as it is generated instead of 1374making it into a big string and returning the string. If you supply 1375the C<OUTPUT> option to C<fill_in>, the value should be a filehandle. 1376The generated text will be printed to this filehandle as it is 1377constructed. For example: 1378 1379 $template->fill_in(OUTPUT => \*STDOUT, ...); 1380 1381fills in the C<$template> as usual, but the results are immediately 1382printed to STDOUT. This may result in the output appearing more 1383quickly than it would have otherwise. 1384 1385If you use C<OUTPUT>, the return value from C<fill_in> is still true on 1386success and false on failure, but the complete text is not returned to 1387the caller. 1388 1389=item C<PREPEND> 1390 1391You can have some Perl code prepended automatically to the beginning 1392of every program fragment. See L<C<PREPEND> feature and using 1393C<strict> in templates> below. 1394 1395=item C<DELIMITERS> 1396 1397If this option is present, its value should be a reference to a list 1398of two strings. The first string is the string that signals the 1399beginning of each program fragment, and the second string is the 1400string that signals the end of each program fragment. See 1401L<"Alternative Delimiters">, below. 1402 1403If you specify C<DELIMITERS> in the call to C<fill_in>, they override 1404any delimiters you set when you created the template object with 1405C<new>. 1406 1407=back 1408 1409=head1 Convenience Functions 1410 1411=head2 C<fill_this_in> 1412 1413The basic way to fill in a template is to create a template object and 1414then call C<fill_in> on it. This is useful if you want to fill in 1415the same template more than once. 1416 1417In some programs, this can be cumbersome. C<fill_this_in> accepts a 1418string, which contains the template, and a list of options, which are 1419passed to C<fill_in> as above. It constructs the template object for 1420you, fills it in as specified, and returns the results. It returns 1421C<undef> and sets C<$Text::Template::ERROR> if it couldn't generate 1422any results. 1423 1424An example: 1425 1426 $Q::name = 'Donald'; 1427 $Q::amount = 141.61; 1428 $Q::part = 'hyoid bone'; 1429 1430 $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q); 1431 Dear {$name}, 1432 You owe me \\${sprintf('%.2f', $amount)}. 1433 Pay or I will break your {$part}. 1434 Love, 1435 Grand Vizopteryx of Irkutsk. 1436 EOM 1437 1438Notice how we included the template in-line in the program by using a 1439`here document' with the C<E<lt>E<lt>> notation. 1440 1441C<fill_this_in> is a deprecated feature. It is only here for 1442backwards compatibility, and may be removed in some far-future version 1443in C<Text::Template>. You should use C<fill_in_string> instead. It 1444is described in the next section. 1445 1446=head2 C<fill_in_string> 1447 1448It is stupid that C<fill_this_in> is a class method. It should have 1449been just an imported function, so that you could omit the 1450C<Text::Template-E<gt>> in the example above. But I made the mistake 1451four years ago and it is too late to change it. 1452 1453C<fill_in_string> is exactly like C<fill_this_in> except that it is 1454not a method and you can omit the C<Text::Template-E<gt>> and just say 1455 1456 print fill_in_string(<<'EOM', ...); 1457 Dear {$name}, 1458 ... 1459 EOM 1460 1461To use C<fill_in_string>, you need to say 1462 1463 use Text::Template 'fill_in_string'; 1464 1465at the top of your program. You should probably use 1466C<fill_in_string> instead of C<fill_this_in>. 1467 1468=head2 C<fill_in_file> 1469 1470If you import C<fill_in_file>, you can say 1471 1472 $text = fill_in_file(filename, ...); 1473 1474The C<...> are passed to C<fill_in> as above. The filename is the 1475name of the file that contains the template you want to fill in. It 1476returns the result text. or C<undef>, as usual. 1477 1478If you are going to fill in the same file more than once in the same 1479program you should use the longer C<new> / C<fill_in> sequence instead. 1480It will be a lot faster because it only has to read and parse the file 1481once. 1482 1483=head2 Including files into templates 1484 1485People always ask for this. ``Why don't you have an include 1486function?'' they want to know. The short answer is this is Perl, and 1487Perl already has an include function. If you want it, you can just put 1488 1489 {qx{cat filename}} 1490 1491into your template. VoilE<agrave>. 1492 1493If you don't want to use C<cat>, you can write a little four-line 1494function that opens a file and dumps out its contents, and call it 1495from the template. I wrote one for you. In the template, you can say 1496 1497 {Text::Template::_load_text(filename)} 1498 1499If that is too verbose, here is a trick. Suppose the template package 1500that you are going to be mentioning in the C<fill_in> call is package 1501C<Q>. Then in the main program, write 1502 1503 *Q::include = \&Text::Template::_load_text; 1504 1505This imports the C<_load_text> function into package C<Q> with the 1506name C<include>. From then on, any template that you fill in with 1507package C<Q> can say 1508 1509 {include(filename)} 1510 1511to insert the text from the named file at that point. If you are 1512using the C<HASH> option instead, just put C<include =E<gt> 1513\&Text::Template::_load_text> into the hash instead of importing it 1514explicitly. 1515 1516Suppose you don't want to insert a plain text file, but rather you 1517want to include one template within another? Just use C<fill_in_file> 1518in the template itself: 1519 1520 {Text::Template::fill_in_file(filename)} 1521 1522You can do the same importing trick if this is too much to type. 1523 1524=head1 Miscellaneous 1525 1526=head2 C<my> variables 1527 1528People are frequently surprised when this doesn't work: 1529 1530 my $recipient = 'The King'; 1531 my $text = fill_in_file('formletter.tmpl'); 1532 1533The text C<The King> doesn't get into the form letter. Why not? 1534Because C<$recipient> is a C<my> variable, and the whole point of 1535C<my> variables is that they're private and inaccessible except in the 1536scope in which they're declared. The template is not part of that 1537scope, so the template can't see C<$recipient>. 1538 1539If that's not the behavior you want, don't use C<my>. C<my> means a 1540private variable, and in this case you don't want the variable to be 1541private. Put the variables into package variables in some other 1542package, and use the C<PACKAGE> option to C<fill_in>: 1543 1544 $Q::recipient = $recipient; 1545 my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q'); 1546 1547or pass the names and values in a hash with the C<HASH> option: 1548 1549 my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient }); 1550 1551=head2 Security Matters 1552 1553All variables are evaluated in the package you specify with the 1554C<PACKAGE> option of C<fill_in>. if you use this option, and if your 1555templates don't do anything egregiously stupid, you won't have to 1556worry that evaluation of the little programs will creep out into the 1557rest of your program and wreck something. 1558 1559Nevertheless, there's really no way (except with C<Safe>) to protect 1560against a template that says 1561 1562 { $Important::Secret::Security::Enable = 0; 1563 # Disable security checks in this program 1564 } 1565 1566or 1567 1568 { $/ = "ho ho ho"; # Sabotage future uses of <FH>. 1569 # $/ is always a global variable 1570 } 1571 1572or even 1573 1574 { system("rm -rf /") } 1575 1576so B<don't> go filling in templates unless you're sure you know what's 1577in them. If you're worried, or you can't trust the person who wrote 1578the template, use the C<SAFE> option. 1579 1580A final warning: program fragments run a small risk of accidentally 1581clobbering local variables in the C<fill_in> function itself. These 1582variables all have names that begin with C<$fi_>, so if you stay away 1583from those names you'll be safe. (Of course, if you're a real wizard 1584you can tamper with them deliberately for exciting effects; this is 1585actually how C<$OUT> works.) I can fix this, but it will make the 1586package slower to do it, so I would prefer not to. If you are worried 1587about this, send me mail and I will show you what to do about it. 1588 1589=head2 Alternative Delimiters 1590 1591Lorenzo Valdettaro pointed out that if you are using C<Text::Template> 1592to generate TeX output, the choice of braces as the program fragment 1593delimiters makes you suffer suffer suffer. Starting in version 1.20, 1594you can change the choice of delimiters to something other than curly 1595braces. 1596 1597In either the C<new()> call or the C<fill_in()> call, you can specify 1598an alternative set of delimiters with the C<DELIMITERS> option. For 1599example, if you would like code fragments to be delimited by C<[@--> 1600and C<--@]> instead of C<{> and C<}>, use 1601 1602 ... DELIMITERS => [ '[@--', '--@]' ], ... 1603 1604Note that these delimiters are I<literal strings>, not regexes. (I 1605tried for regexes, but it complicates the lexical analysis too much.) 1606Note also that C<DELIMITERS> disables the special meaning of the 1607backslash, so if you want to include the delimiters in the literal 1608text of your template file, you are out of luck---it is up to you to 1609choose delimiters that do not conflict with what you are doing. The 1610delimiter strings may still appear inside of program fragments as long 1611as they nest properly. This means that if for some reason you 1612absolutely must have a program fragment that mentions one of the 1613delimiters, like this: 1614 1615 [@-- 1616 print "Oh no, a delimiter: --@]\n" 1617 --@] 1618 1619you may be able to make it work by doing this instead: 1620 1621 [@-- 1622 # Fake matching delimiter in a comment: [@-- 1623 print "Oh no, a delimiter: --@]\n" 1624 --@] 1625 1626It may be safer to choose delimiters that begin with a newline 1627character. 1628 1629Because the parsing of templates is simplified by the absence of 1630backslash escapes, using alternative C<DELIMITERS> may speed up the 1631parsing process by 20-25%. This shows that my original choice of C<{> 1632and C<}> was very bad. 1633 1634=head2 C<PREPEND> feature and using C<strict> in templates 1635 1636Suppose you would like to use C<strict> in your templates to detect 1637undeclared variables and the like. But each code fragment is a 1638separate lexical scope, so you have to turn on C<strict> at the top of 1639each and every code fragment: 1640 1641 { use strict; 1642 use vars '$foo'; 1643 $foo = 14; 1644 ... 1645 } 1646 1647 ... 1648 1649 { # we forgot to put `use strict' here 1650 my $result = $boo + 12; # $boo is misspelled and should be $foo 1651 # No error is raised on `$boo' 1652 } 1653 1654Because we didn't put C<use strict> at the top of the second fragment, 1655it was only active in the first fragment, and we didn't get any 1656C<strict> checking in the second fragment. Then we misspelled C<$foo> 1657and the error wasn't caught. 1658 1659C<Text::Template> version 1.22 and higher has a new feature to make 1660this easier. You can specify that any text at all be automatically 1661added to the beginning of each program fragment. 1662 1663When you make a call to C<fill_in>, you can specify a 1664 1665 PREPEND => 'some perl statements here' 1666 1667option; the statements will be prepended to each program fragment for 1668that one call only. Suppose that the C<fill_in> call included a 1669 1670 PREPEND => 'use strict;' 1671 1672option, and that the template looked like this: 1673 1674 { use vars '$foo'; 1675 $foo = 14; 1676 ... 1677 } 1678 1679 ... 1680 1681 { my $result = $boo + 12; # $boo is misspelled and should be $foo 1682 ... 1683 } 1684 1685The code in the second fragment would fail, because C<$boo> has not 1686been declared. C<use strict> was implied, even though you did not 1687write it explicitly, because the C<PREPEND> option added it for you 1688automatically. 1689 1690There are three other ways to do this. At the time you create the 1691template object with C<new>, you can also supply a C<PREPEND> option, 1692in which case the statements will be prepended each time you fill in 1693that template. If the C<fill_in> call has its own C<PREPEND> option, 1694this overrides the one specified at the time you created the 1695template. Finally, you can make the class method call 1696 1697 Text::Template->always_prepend('perl statements'); 1698 1699If you do this, then call calls to C<fill_in> for I<any> template will 1700attach the perl statements to the beginning of each program fragment, 1701except where overridden by C<PREPEND> options to C<new> or C<fill_in>. 1702 1703An alternative to adding "use strict;" to the PREPEND option, you can 1704pass STRICT => 1 to fill_in when also passing the HASH option. 1705 1706Suppose that the C<fill_in> call included both 1707 1708 HASH => {$foo => ''} and 1709 STRICT => 1 1710 1711options, and that the template looked like this: 1712 1713 { 1714 $foo = 14; 1715 ... 1716 } 1717 1718 ... 1719 1720 { my $result = $boo + 12; # $boo is misspelled and should be $foo 1721 ... 1722 } 1723 1724The code in the second fragment would fail, because C<$boo> has not 1725been declared. C<use strict> was implied, even though you did not 1726write it explicitly, because the C<STRICT> option added it for you 1727automatically. Any variable referenced in the template that is not in the 1728C<HASH> option will be an error. 1729 1730=head2 Prepending in Derived Classes 1731 1732This section is technical, and you should skip it on the first few 1733readings. 1734 1735Normally there are three places that prepended text could come from. 1736It could come from the C<PREPEND> option in the C<fill_in> call, from 1737the C<PREPEND> option in the C<new> call that created the template 1738object, or from the argument of the C<always_prepend> call. 1739C<Text::Template> looks for these three things in order and takes the 1740first one that it finds. 1741 1742In a subclass of C<Text::Template>, this last possibility is 1743ambiguous. Suppose C<S> is a subclass of C<Text::Template>. Should 1744 1745 Text::Template->always_prepend(...); 1746 1747affect objects in class C<Derived>? The answer is that you can have it 1748either way. 1749 1750The C<always_prepend> value for C<Text::Template> is normally stored 1751in a hash variable named C<%GLOBAL_PREPEND> under the key 1752C<Text::Template>. When C<Text::Template> looks to see what text to 1753prepend, it first looks in the template object itself, and if not, it 1754looks in C<$GLOBAL_PREPEND{I<class>}> where I<class> is the class to 1755which the template object belongs. If it doesn't find any value, it 1756looks in C<$GLOBAL_PREPEND{'Text::Template'}>. This means that 1757objects in class C<Derived> I<will> be affected by 1758 1759 Text::Template->always_prepend(...); 1760 1761I<unless> there is also a call to 1762 1763 Derived->always_prepend(...); 1764 1765So when you're designing your derived class, you can arrange to have 1766your objects ignore C<Text::Template::always_prepend> calls by simply 1767putting C<Derived-E<gt>always_prepend('')> at the top of your module. 1768 1769Of course, there is also a final escape hatch: Templates support a 1770C<prepend_text> that is used to look up the appropriate text to be 1771prepended at C<fill_in> time. Your derived class can override this 1772method to get an arbitrary effect. 1773 1774=head2 JavaScript 1775 1776Jennifer D. St Clair asks: 1777 1778 > Most of my pages contain JavaScript and Stylesheets. 1779 > How do I change the template identifier? 1780 1781Jennifer is worried about the braces in the JavaScript being taken as 1782the delimiters of the Perl program fragments. Of course, disaster 1783will ensue when perl tries to evaluate these as if they were Perl 1784programs. The best choice is to find some unambiguous delimiter 1785strings that you can use in your template instead of curly braces, and 1786then use the C<DELIMITERS> option. However, if you can't do this for 1787some reason, there are two easy workarounds: 1788 17891. You can put C<\> in front of C<{>, C<}>, or C<\> to remove its 1790special meaning. So, for example, instead of 1791 1792 if (br== "n3") { 1793 // etc. 1794 } 1795 1796you can put 1797 1798 if (br== "n3") \{ 1799 // etc. 1800 \} 1801 1802and it'll come out of the template engine the way you want. 1803 1804But here is another method that is probably better. To see how it 1805works, first consider what happens if you put this into a template: 1806 1807 { 'foo' } 1808 1809Since it's in braces, it gets evaluated, and obviously, this is going 1810to turn into 1811 1812 foo 1813 1814So now here's the trick: In Perl, C<q{...}> is the same as C<'...'>. 1815So if we wrote 1816 1817 {q{foo}} 1818 1819it would turn into 1820 1821 foo 1822 1823So for your JavaScript, just write 1824 1825 {q{if (br== "n3") { 1826 // etc. 1827 }} 1828 } 1829 1830and it'll come out as 1831 1832 if (br== "n3") { 1833 // etc. 1834 } 1835 1836which is what you want. 1837 1838head2 Shut Up! 1839 1840People sometimes try to put an initialization section at the top of 1841their templates, like this: 1842 1843 { ... 1844 $var = 17; 1845 } 1846 1847Then they complain because there is a C<17> at the top of the output 1848that they didn't want to have there. 1849 1850Remember that a program fragment is replaced with its own return 1851value, and that in Perl the return value of a code block is the value 1852of the last expression that was evaluated, which in this case is 17. 1853If it didn't do that, you wouldn't be able to write C<{$recipient}> 1854and have the recipient filled in. 1855 1856To prevent the 17 from appearing in the output is very simple: 1857 1858 { ... 1859 $var = 17; 1860 ''; 1861 } 1862 1863Now the last expression evaluated yields the empty string, which is 1864invisible. If you don't like the way this looks, use 1865 1866 { ... 1867 $var = 17; 1868 ($SILENTLY); 1869 } 1870 1871instead. Presumably, C<$SILENTLY> has no value, so nothing will be 1872interpolated. This is what is known as a `trick'. 1873 1874=head2 Compatibility 1875 1876Every effort has been made to make this module compatible with older 1877versions. The only known exceptions follow: 1878 1879The output format of the default C<BROKEN> subroutine has changed 1880twice, most recently between versions 1.31 and 1.40. 1881 1882Starting in version 1.10, the C<$OUT> variable is arrogated for a 1883special meaning. If you had templates before version 1.10 that 1884happened to use a variable named C<$OUT>, you will have to change them 1885to use some other variable or all sorts of strangeness will result. 1886 1887Between versions 0.1b and 1.00 the behavior of the \ metacharacter 1888changed. In 0.1b, \\ was special everywhere, and the template 1889processor always replaced it with a single backslash before passing 1890the code to Perl for evaluation. The rule now is more complicated but 1891probably more convenient. See the section on backslash processing, 1892below, for a full discussion. 1893 1894=head2 Backslash Processing 1895 1896In C<Text::Template> beta versions, the backslash was special whenever 1897it appeared before a brace or another backslash. That meant that 1898while C<{"\n"}> did indeed generate a newline, C<{"\\"}> did not 1899generate a backslash, because the code passed to Perl for evaluation 1900was C<"\"> which is a syntax error. If you wanted a backslash, you 1901would have had to write C<{"\\\\"}>. 1902 1903In C<Text::Template> versions 1.00 through 1.10, there was a bug: 1904Backslash was special everywhere. In these versions, C<{"\n"}> 1905generated the letter C<n>. 1906 1907The bug has been corrected in version 1.11, but I did not go back to 1908exactly the old rule, because I did not like the idea of having to 1909write C<{"\\\\"}> to get one backslash. The rule is now more 1910complicated to remember, but probably easier to use. The rule is now: 1911Backslashes are always passed to Perl unchanged I<unless> they occur 1912as part of a sequence like C<\\\\\\{> or C<\\\\\\}>. In these 1913contexts, they are special; C<\\> is replaced with C<\>, and C<\{> and 1914C<\}> signal a literal brace. 1915 1916Examples: 1917 1918 \{ foo \} 1919 1920is I<not> evaluated, because the C<\> before the braces signals that 1921they should be taken literally. The result in the output looks like this: 1922 1923 { foo } 1924 1925This is a syntax error: 1926 1927 { "foo}" } 1928 1929because C<Text::Template> thinks that the code ends at the first C<}>, 1930and then gets upset when it sees the second one. To make this work 1931correctly, use 1932 1933 { "foo\}" } 1934 1935This passes C<"foo}"> to Perl for evaluation. Note there's no C<\> in 1936the evaluated code. If you really want a C<\> in the evaluated code, 1937use 1938 1939 { "foo\\\}" } 1940 1941This passes C<"foo\}"> to Perl for evaluation. 1942 1943Starting with C<Text::Template> version 1.20, backslash processing is 1944disabled if you use the C<DELIMITERS> option to specify alternative 1945delimiter strings. 1946 1947=head2 A short note about C<$Text::Template::ERROR> 1948 1949In the past some people have fretted about `violating the package 1950boundary' by examining a variable inside the C<Text::Template> 1951package. Don't feel this way. C<$Text::Template::ERROR> is part of 1952the published, official interface to this package. It is perfectly OK 1953to inspect this variable. The interface is not going to change. 1954 1955If it really, really bothers you, you can import a function called 1956C<TTerror> that returns the current value of the C<$ERROR> variable. 1957So you can say: 1958 1959 use Text::Template 'TTerror'; 1960 1961 my $template = Text::Template->new(SOURCE => $filename); 1962 unless ($template) { 1963 my $err = TTerror; 1964 die "Couldn't make template: $err; aborting"; 1965 } 1966 1967I don't see what benefit this has over just doing this: 1968 1969 use Text::Template; 1970 1971 my $template = Text::Template->new(SOURCE => $filename) 1972 or die "Couldn't make template: $Text::Template::ERROR; aborting"; 1973 1974But if it makes you happy to do it that way, go ahead. 1975 1976=head2 Sticky Widgets in Template Files 1977 1978The C<CGI> module provides functions for `sticky widgets', which are 1979form input controls that retain their values from one page to the 1980next. Sometimes people want to know how to include these widgets 1981into their template output. 1982 1983It's totally straightforward. Just call the C<CGI> functions from 1984inside the template: 1985 1986 { $q->checkbox_group(NAME => 'toppings', 1987 LINEBREAK => true, 1988 COLUMNS => 3, 1989 VALUES => \@toppings, 1990 ); 1991 } 1992 1993=head2 Automatic preprocessing of program fragments 1994 1995It may be useful to preprocess the program fragments before they are 1996evaluated. See C<Text::Template::Preprocess> for more details. 1997 1998=head2 Automatic postprocessing of template hunks 1999 2000It may be useful to process hunks of output before they are appended to 2001the result text. For this, subclass and replace the C<append_text_to_result> 2002method. It is passed a list of pairs with these entries: 2003 2004 handle - a filehandle to which to print the desired output 2005 out - a ref to a string to which to append, to use if handle is not given 2006 text - the text that will be appended 2007 type - where the text came from: TEXT for literal text, PROG for code 2008 2009=head1 HISTORY 2010 2011Originally written by Mark Jason Dominus, Plover Systems (versions 0.01 - 1.46) 2012 2013Maintainership transferred to Michael Schout E<lt>mschout@cpan.orgE<gt> in version 20141.47 2015 2016=head1 THANKS 2017 2018Many thanks to the following people for offering support, 2019encouragement, advice, bug reports, and all the other good stuff. 2020 2021=over 4 2022 2023=item * 2024 2025Andrew G Wood 2026 2027=item * 2028 2029Andy Wardley 2030 2031=item * 2032 2033António Aragão 2034 2035=item * 2036 2037Archie Warnock 2038 2039=item * 2040 2041Bek Oberin 2042 2043=item * 2044 2045Bob Dougherty 2046 2047=item * 2048 2049Brian C. Shensky 2050 2051=item * 2052 2053Chris Nandor 2054 2055=item * 2056 2057Chris Wesley 2058 2059=item * 2060 2061Chris.Brezil 2062 2063=item * 2064 2065Daini Xie 2066 2067=item * 2068 2069Dan Franklin 2070 2071=item * 2072 2073Daniel LaLiberte 2074 2075=item * 2076 2077David H. Adler 2078 2079=item * 2080 2081David Marshall 2082 2083=item * 2084 2085Dennis Taylor 2086 2087=item * 2088 2089Donald L. Greer Jr. 2090 2091=item * 2092 2093Dr. Frank Bucolo 2094 2095=item * 2096 2097Fred Steinberg 2098 2099=item * 2100 2101Gene Damon 2102 2103=item * 2104 2105Hans Persson 2106 2107=item * 2108 2109Hans Stoop 2110 2111=item * 2112 2113Itamar Almeida de Carvalho 2114 2115=item * 2116 2117James H. Thompson 2118 2119=item * 2120 2121James Mastros 2122 2123=item * 2124 2125Jarko Hietaniemi 2126 2127=item * 2128 2129Jason Moore 2130 2131=item * 2132 2133Jennifer D. St Clair 2134 2135=item * 2136 2137Joel Appelbaum 2138 2139=item * 2140 2141Joel Meulenberg 2142 2143=item * 2144 2145Jonathan Roy 2146 2147=item * 2148 2149Joseph Cheek 2150 2151=item * 2152 2153Juan E. Camacho 2154 2155=item * 2156 2157Kevin Atteson 2158 2159=item * 2160 2161Kevin Madsen 2162 2163=item * 2164 2165Klaus Arnhold 2166 2167=item * 2168 2169Larry Virden 2170 2171=item * 2172 2173Lieven Tomme 2174 2175=item * 2176 2177Lorenzo Valdettaro 2178 2179=item * 2180 2181Marek Grac 2182 2183=item * 2184 2185Matt Womer 2186 2187=item * 2188 2189Matt X. Hunter 2190 2191=item * 2192 2193Michael G Schwern 2194 2195=item * 2196 2197Michael J. Suzio 2198 2199=item * 2200 2201Michaely Yeung 2202 2203=item * 2204 2205Michelangelo Grigni 2206 2207=item * 2208 2209Mike Brodhead 2210 2211=item * 2212 2213Niklas Skoglund 2214 2215=item * 2216 2217Randal L. Schwartz 2218 2219=item * 2220 2221Reuven M. Lerner 2222 2223=item * 2224 2225Robert M. Ioffe 2226 2227=item * 2228 2229Ron Pero 2230 2231=item * 2232 2233San Deng 2234 2235=item * 2236 2237Sean Roehnelt 2238 2239=item * 2240 2241Sergey Myasnikov 2242 2243=item * 2244 2245Shabbir J. Safdar 2246 2247=item * 2248 2249Shad Todd 2250 2251=item * 2252 2253Steve Palincsar 2254 2255=item * 2256 2257Tim Bunce 2258 2259=item * 2260 2261Todd A. Green 2262 2263=item * 2264 2265Tom Brown 2266 2267=item * 2268 2269Tom Henry 2270 2271=item * 2272 2273Tom Snee 2274 2275=item * 2276 2277Trip Lilley 2278 2279=item * 2280 2281Uwe Schneider 2282 2283=item * 2284 2285Val Luck 2286 2287=item * 2288 2289Yannis Livassof 2290 2291=item * 2292 2293Yonat Sharon 2294 2295=item * 2296 2297Zac Hansen 2298 2299=item * 2300 2301gary at dls.net 2302 2303=back 2304 2305Special thanks to: 2306 2307=over 2 2308 2309=item Jonathan Roy 2310 2311for telling me how to do the C<Safe> support (I spent two years 2312worrying about it, and then Jonathan pointed out that it was trivial.) 2313 2314=item Ranjit Bhatnagar 2315 2316for demanding less verbose fragments like they have in ASP, for 2317helping me figure out the Right Thing, and, especially, for talking me 2318out of adding any new syntax. These discussions resulted in the 2319C<$OUT> feature. 2320 2321=back 2322 2323=head2 Bugs and Caveats 2324 2325C<my> variables in C<fill_in> are still susceptible to being clobbered 2326by template evaluation. They all begin with C<fi_>, so avoid those 2327names in your templates. 2328 2329The line number information will be wrong if the template's lines are 2330not terminated by C<"\n">. You should let me know if this is a 2331problem. If you do, I will fix it. 2332 2333The C<$OUT> variable has a special meaning in templates, so you cannot 2334use it as if it were a regular variable. 2335 2336There are not quite enough tests in the test suite. 2337 2338=head1 SOURCE 2339 2340The development version is on github at L<https://https://github.com/mschout/perl-text-template> 2341and may be cloned from L<git://https://github.com/mschout/perl-text-template.git> 2342 2343=head1 BUGS 2344 2345Please report any bugs or feature requests on the bugtracker website 2346L<https://github.com/mschout/perl-text-template/issues> 2347 2348When submitting a bug or request, please include a test-file or a 2349patch to an existing test-file that illustrates the bug or desired 2350feature. 2351 2352=head1 AUTHOR 2353 2354Michael Schout <mschout@cpan.org> 2355 2356=head1 COPYRIGHT AND LICENSE 2357 2358This software is copyright (c) 2013 by Mark Jason Dominus <mjd@cpan.org>. 2359 2360This is free software; you can redistribute it and/or modify it under 2361the same terms as the Perl 5 programming language system itself. 2362 2363=cut 2364