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