1#============================================================= -*-perl-*- 2# 3# Template::Manual::Config 4# 5# AUTHOR 6# Andy Wardley <abw@wardley.org> 7# 8# COPYRIGHT 9# Copyright (C) 1996-2020 Andy Wardley. All Rights Reserved. 10# 11# This module is free software; you can redistribute it and/or 12# modify it under the same terms as Perl itself. 13# 14#======================================================================== 15 16=head1 NAME 17 18Template::Manual::Config - Configuration options 19 20=head1 Template Style and Parsing Options 21 22=head2 ENCODING 23 24The C<ENCODING> option specifies the template files' character encoding: 25 26 my $template = Template->new({ 27 ENCODING => 'utf8', 28 }); 29 30A template which starts with a Unicode byte order mark (BOM) will have its 31encoding detected automatically. 32 33=head2 START_TAG, END_TAG 34 35The C<START_TAG> and C<END_TAG> options are used to specify character 36sequences or regular expressions that mark the start and end of inline 37template directives. The default values for C<START_TAG> and C<END_TAG> are 38'C<[%>' and 'C<%]>' respectively, giving us the familiar directive style: 39 40 [% example %] 41 42Any Perl regex characters can be used and therefore should be escaped 43(or use the Perl C<quotemeta> function) if they are intended to 44represent literal characters. 45 46 my $template = Template->new({ 47 START_TAG => quotemeta('<+'), 48 END_TAG => quotemeta('+>'), 49 }); 50 51Example: 52 53 <+ INCLUDE foobar +> 54 55The C<TAGS> directive can also be used to set the C<START_TAG> and C<END_TAG> values 56on a per-template file basis. 57 58 [% TAGS <+ +> %] 59 60=head2 OUTLINE_TAG 61 62The C<OUTLINE_TAG> option can be used to enable single-line "outline" directives. 63 64 my $template = Template->new({ 65 OUTLINE_TAG => '%%', 66 }); 67 68This allows you to use both inline and outline tags like so: 69 70 %% IF user 71 Hello [% user.name %] 72 %% END 73 74The C<OUTLINE_TAG> string (or regex) must appear at the start of a line. The 75directive continues until the end of the line. The newline character at the 76end of the line is considered to be the invisible end-of-directive marker and 77is removed. 78 79=head2 TAG_STYLE 80 81The C<TAG_STYLE> option can be used to set both C<START_TAG> and C<END_TAG> 82according to pre-defined tag styles. 83 84 my $template = Template->new({ 85 TAG_STYLE => 'star', 86 }); 87 88Available styles are: 89 90 template [% ... %] (default) 91 template1 [% ... %] or %% ... %% (TT version 1) 92 metatext %% ... %% (Text::MetaText) 93 star [* ... *] (TT alternate) 94 php <? ... ?> (PHP) 95 asp <% ... %> (ASP) 96 mason <% ... > (HTML::Mason) 97 html <!-- ... --> (HTML comments) 98 99The C<outline> style uses the default markers for C<START_TAG> and C<END_TAG> 100(C<[%> and C<%]> respectively) and additionally defines C<OUTLINE_TAG> to 101be C<%%>. 102 103 my $template = Template->new({ 104 TAG_STYLE => 'outline', 105 }); 106 107This allows you to use both inline and outline tags like so: 108 109 %% IF user 110 Hello [% user.name %] 111 %% END 112 113Any values specified for C<START_TAG>, C<END_TAG> and/or C<OUTLINE_TAG> 114will override those defined by a C<TAG_STYLE>. 115 116The C<TAGS> directive may also be used to set a C<TAG_STYLE> 117 118 [% TAGS html %] 119 <!-- INCLUDE header --> 120 121=head2 PRE_CHOMP, POST_CHOMP 122 123Anything outside a directive tag is considered plain text and is 124generally passed through unaltered (but see the L<INTERPOLATE> option). 125This includes all whitespace and newlines characters surrounding 126directive tags. Directives that don't generate any output will leave 127gaps in the output document. 128 129Example: 130 131 Foo 132 [% a = 10 %] 133 Bar 134 135Output: 136 137 Foo 138 139 Bar 140 141The C<PRE_CHOMP> and C<POST_CHOMP> options can help to clean up some of this 142extraneous whitespace. Both are disabled by default. 143 144 my $template = Template->new({ 145 PRE_CHOMP => 1, 146 POST_CHOMP => 1, 147 }); 148 149With C<PRE_CHOMP> set to C<1>, the newline and whitespace preceding a directive 150at the start of a line will be deleted. This has the effect of 151concatenating a line that starts with a directive onto the end of the 152previous line. 153 154 Foo <----------. 155 | 156 ,---(PRE_CHOMP)----' 157 | 158 `-- [% a = 10 %] --. 159 | 160 ,---(POST_CHOMP)---' 161 | 162 `-> Bar 163 164With C<POST_CHOMP> set to C<1>, any whitespace after a directive up to and 165including the newline will be deleted. This has the effect of joining 166a line that ends with a directive onto the start of the next line. 167 168If C<PRE_CHOMP> or C<POST_CHOMP> is set to C<2>, all whitespace including any 169number of newline will be removed and replaced with a single space. 170This is useful for HTML, where (usually) a contiguous block of 171whitespace is rendered the same as a single space. 172 173With C<PRE_CHOMP> or C<POST_CHOMP> set to C<3>, all adjacent whitespace 174(including newlines) will be removed entirely. 175 176These values are defined as C<CHOMP_NONE>, C<CHOMP_ONE>, C<CHOMP_COLLAPSE> and 177C<CHOMP_GREEDY> constants in the L<Template::Constants> module. C<CHOMP_ALL> 178is also defined as an alias for C<CHOMP_ONE> to provide backwards 179compatibility with earlier version of the Template Toolkit. 180 181Additionally the chomp tag modifiers listed below may also be used for 182the C<PRE_CHOMP> and C<POST_CHOMP> configuration. 183 184 my $template = Template->new({ 185 PRE_CHOMP => '~', 186 POST_CHOMP => '-', 187 }); 188 189C<PRE_CHOMP> and C<POST_CHOMP> can be activated for individual directives by 190placing a 'C<->' immediately at the start and/or end of the directive. 191 192 [% FOREACH user IN userlist %] 193 [%- user -%] 194 [% END %] 195 196This has the same effect as C<CHOMP_ONE> in removing all whitespace 197before or after the directive up to and including the newline. The 198template will be processed as if written: 199 200 [% FOREACH user IN userlist %][% user %][% END %] 201 202To remove all whitespace including any number of newlines, use the ('C<~>') 203tilde character instead. 204 205 [% FOREACH user IN userlist %] 206 207 [%~ user ~%] 208 209 [% END %] 210 211To collapse all whitespace to a single space, use the 'C<=>' equals sign character. 212 213 [% FOREACH user IN userlist %] 214 215 [%= user =%] 216 217 [% END %] 218 219Here the template is processed as if written: 220 221 [% FOREACH user IN userlist %] [% user %] [% END %] 222 223If you have C<PRE_CHOMP> or C<POST_CHOMP> set as configuration options then 224you can use the 'C<+>' plus sign to disable any chomping options (i.e. leave the 225whitespace intact) on a per-directive basis. 226 227 [% FOREACH user IN userlist %] 228 User: [% user +%] 229 [% END %] 230 231With C<POST_CHOMP> set to C<CHOMP_ONE>, the above example would be parsed as 232if written: 233 234 [% FOREACH user IN userlist %]User: [% user %] 235 [% END %] 236 237For reference, the C<PRE_CHOMP> and C<POST_CHOMP> configuration options may be 238set to any of the following: 239 240 Constant Value Tag Modifier 241 ---------------------------------- 242 CHOMP_NONE 0 + 243 CHOMP_ONE 1 - 244 CHOMP_COLLAPSE 2 = 245 CHOMP_GREEDY 3 ~ 246 247=head2 TRIM 248 249The C<TRIM> option can be set to have any leading and trailing whitespace 250automatically removed from the output of all template files and C<BLOCK>s. 251 252By example, the following C<BLOCK> definition 253 254 [% BLOCK foo %] 255 Line 1 of foo 256 [% END %] 257 258will be processed is as "C<\nLine 1 of foo\n>". When C<INCLUDE>d, the surrounding 259newlines will also be introduced. 260 261 before 262 [% INCLUDE foo %] 263 after 264 265Generated output: 266 267 before 268 269 Line 1 of foo 270 271 after 272 273With the C<TRIM> option set to any true value, the leading and trailing 274newlines (which count as whitespace) will be removed from the output 275of the C<BLOCK>. 276 277 before 278 Line 1 of foo 279 after 280 281The C<TRIM> option is disabled (C<0>) by default. 282 283=head2 INTERPOLATE 284 285The C<INTERPOLATE> flag, when set to any true value will cause variable 286references in plain text (i.e. not surrounded by C<START_TAG> and C<END_TAG>) 287to be recognised and interpolated accordingly. 288 289 my $template = Template->new({ 290 INTERPOLATE => 1, 291 }); 292 293Variables should be prefixed by a 'C<$>' dollar sign to identify them. 294Curly braces 'C<{>' and 'C<}>' 295can be used in the familiar Perl/shell style to explicitly scope the 296variable name where required. 297 298 # INTERPOLATE => 0 299 <a href="http://[% server %]/[% help %]"> 300 <img src="[% images %]/help.gif"></a> 301 [% myorg.name %] 302 303 # INTERPOLATE => 1 304 <a href="http://$server/$help"> 305 <img src="$images/help.gif"></a> 306 $myorg.name 307 308 # explicit scoping with { } 309 <img src="$images/${icon.next}.gif"> 310 311Note that a limitation in Perl's regex engine restricts the maximum length 312of an interpolated template to around 32 kilobytes or possibly less. Files 313that exceed this limit in size will typically cause Perl to dump core with 314a segmentation fault. If you routinely process templates of this size 315then you should disable C<INTERPOLATE> or split the templates in several 316smaller files or blocks which can then be joined backed together via 317C<PROCESS> or C<INCLUDE>. 318 319=head2 ANYCASE 320 321By default, directive keywords should be expressed in UPPER CASE. The 322C<ANYCASE> option can be set to allow directive keywords to be specified 323in any case. 324 325 # ANYCASE => 0 (default) 326 [% INCLUDE foobar %] # OK 327 [% include foobar %] # ERROR 328 [% include = 10 %] # OK, 'include' is a variable 329 330 # ANYCASE => 1 331 [% INCLUDE foobar %] # OK 332 [% include foobar %] # OK 333 [% include = 10 %] # ERROR, 'include' is reserved word 334 335One side-effect of enabling C<ANYCASE> is that you cannot use a variable 336of the same name as a reserved word, regardless of case. The reserved 337words are currently: 338 339 GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER 340 IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE 341 USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META 342 TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP 343 CLEAR TO STEP AND OR NOT MOD DIV END 344 345The only lower case reserved words that cannot be used for variables, 346regardless of the C<ANYCASE> option, are the operators: 347 348 and or not mod div 349 350=head1 Template Files and Blocks 351 352=head2 INCLUDE_PATH 353 354The C<INCLUDE_PATH> is used to specify one or more directories in which 355template files are located. When a template is requested that isn't 356defined locally as a C<BLOCK>, each of the C<INCLUDE_PATH> directories is 357searched in turn to locate the template file. Multiple directories 358can be specified as a reference to a list or as a single string where 359each directory is delimited by the 'C<:>' colon character. 360 361 my $template = Template->new({ 362 INCLUDE_PATH => '/usr/local/templates', 363 }); 364 365 my $template = Template->new({ 366 INCLUDE_PATH => '/usr/local/templates:/tmp/my/templates', 367 }); 368 369 my $template = Template->new({ 370 INCLUDE_PATH => [ '/usr/local/templates', 371 '/tmp/my/templates' ], 372 }); 373 374On Win32 systems, a little extra magic is invoked, ignoring delimiters 375that have 'C<:>' colon followed by a 'C</>' slash or 'C<\>' blackslash. 376This avoids confusion when using directory names like 'C<C:\Blah Blah>'. 377 378When specified as a list, the C<INCLUDE_PATH> path can contain elements 379which dynamically generate a list of C<INCLUDE_PATH> directories. These 380generator elements can be specified as a reference to a subroutine or 381an object which implements a C<paths()> method. 382 383 my $template = Template->new({ 384 INCLUDE_PATH => [ '/usr/local/templates', 385 \&incpath_generator, 386 My::IncPath::Generator->new( ... ) ], 387 }); 388 389Each time a template is requested and the C<INCLUDE_PATH> examined, the 390subroutine or object method will be called. A reference to a list of 391directories should be returned. Generator subroutines should report 392errors using C<die()>. Generator objects should return undef and make an 393error available via its C<error()> method. 394 395For example: 396 397 sub incpath_generator { 398 # ...some code... 399 400 if ($all_is_well) { 401 return \@list_of_directories; 402 } 403 else { 404 die "cannot generate INCLUDE_PATH...\n"; 405 } 406 } 407 408or: 409 410 package My::IncPath::Generator; 411 412 # Template::Base (or Class::Base) provides error() method 413 use Template::Base; 414 use base qw( Template::Base ); 415 416 sub paths { 417 my $self = shift; 418 419 # ...some code... 420 421 if ($all_is_well) { 422 return \@list_of_directories; 423 } 424 else { 425 return $self->error("cannot generate INCLUDE_PATH...\n"); 426 } 427 } 428 429 1; 430 431=head2 DELIMITER 432 433Used to provide an alternative delimiter character sequence for 434separating paths specified in the C<INCLUDE_PATH>. The default 435value for C<DELIMITER> is the 'C<:>' colon character. 436 437 my $template = Template->new({ 438 DELIMITER => '; ', 439 INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN', 440 }); 441 442On Win32 systems, the default delimiter is a little more intelligent, 443splitting paths only on 'C<:>' colon characters that aren't followed by a 444'C</>' slash character. 445This means that the following should work as planned, splitting the 446C<INCLUDE_PATH> into 2 separate directories, C<C:/foo> and C<C:/bar>. 447 448 # on Win32 only 449 my $template = Template->new({ 450 INCLUDE_PATH => 'C:/Foo:C:/Bar' 451 }); 452 453However, if you're using Win32 then it's recommended that you 454explicitly set the C<DELIMITER> character to something else (e.g. 'C<;>' semicolon) 455rather than rely on this subtle magic. 456 457=head2 ABSOLUTE 458 459The C<ABSOLUTE> flag is used to indicate if templates specified with 460absolute filenames (e.g. 'C</foo/bar>') should be processed. It is 461disabled by default and any attempt to load a template by such a 462name will cause a 'C<file>' exception to be raised. 463 464 my $template = Template->new({ 465 ABSOLUTE => 1, 466 }); 467 468 # this is why it's disabled by default 469 [% INSERT /etc/passwd %] 470 471On Win32 systems, the regular expression for matching absolute 472pathnames is tweaked slightly to also detect filenames that start 473with a driver letter and colon, such as: 474 475 C:/Foo/Bar 476 477=head2 RELATIVE 478 479The C<RELATIVE> flag is used to indicate if templates specified with 480filenames relative to the current directory (e.g. 'C<./foo/bar>' or 481'C<../../some/where/else>') should be loaded. It is also disabled by 482default, and will raise a 'C<file>' error if such template names are 483encountered. 484 485 my $template = Template->new({ 486 RELATIVE => 1, 487 }); 488 489 [% INCLUDE ../logs/error.log %] 490 491=head2 DEFAULT 492 493The C<DEFAULT> option can be used to specify a default template which should 494be used whenever a specified template can't be found in the C<INCLUDE_PATH>. 495 496 my $template = Template->new({ 497 DEFAULT => 'notfound.html', 498 }); 499 500If a non-existent template is requested through the Template 501L<process()|Template#process()> method, or by an C<INCLUDE>, C<PROCESS> or 502C<WRAPPER> directive, then the C<DEFAULT> template will instead be processed, if 503defined. Note that the C<DEFAULT> template is not used when templates are 504specified with absolute or relative filenames, or as a reference to a input 505file handle or text string. 506 507=head2 BLOCKS 508 509The C<BLOCKS> option can be used to pre-define a default set of template 510blocks. These should be specified as a reference to a hash array 511mapping template names to template text, subroutines or L<Template::Document> 512objects. 513 514 my $template = Template->new({ 515 BLOCKS => { 516 header => 'The Header. [% title %]', 517 footer => sub { return $some_output_text }, 518 another => Template::Document->new({ ... }), 519 }, 520 }); 521 522=head2 VIEWS 523 524The VIEWS option can be used to define one or more L<Template::View> 525objects. They can be specified as a reference to a hash array or list 526reference. 527 528 my $template = Template->new({ 529 VIEWS => { 530 my_view => { prefix => 'my_templates/' }, 531 }, 532 }); 533 534Be aware of the fact that Perl's hash array are unordered, so if you want to 535specify multiple views of which one or more are based on other views, then 536you should use a list reference to preserve the order of definition. 537 538 my $template = Template->new({ 539 VIEWS => [ 540 bottom => { prefix => 'bottom/' }, 541 middle => { prefix => 'middle/', base => 'bottom' }, 542 top => { prefix => 'top/', base => 'middle' }, 543 ], 544 }); 545 546=head2 AUTO_RESET 547 548The C<AUTO_RESET> option is set by default and causes the local C<BLOCKS> 549cache for the L<Template::Context> object to be reset on each call to the 550Template L<process()|Template#process()> method. This ensures that any C<BLOCK>s 551defined within a template will only persist until that template is finished 552processing. This prevents C<BLOCK>s defined in one processing request from 553interfering with other independent requests subsequently processed by the same 554context object. 555 556The C<BLOCKS> item may be used to specify a default set of block definitions 557for the L<Template::Context> object. Subsequent C<BLOCK> definitions in 558templates will over-ride these but they will be reinstated on each reset if 559C<AUTO_RESET> is enabled (default), or if the L<Template::Context> 560L<reset()|Template::Context#reset()> method is called. 561 562=head2 RECURSION 563 564The template processor will raise a file exception if it detects 565direct or indirect recursion into a template. Setting this option to 566any true value will allow templates to include each other recursively. 567 568=head1 Template Variables 569 570=head2 VARIABLES 571 572The C<VARIABLES> option (or C<PRE_DEFINE> - they're equivalent) can be used 573to specify a hash array of template variables that should be used to 574pre-initialise the stash when it is created. These items are ignored 575if the C<STASH> item is defined. 576 577 my $template = Template->new({ 578 VARIABLES => { 579 title => 'A Demo Page', 580 author => 'Joe Random Hacker', 581 version => 3.14, 582 }, 583 }; 584 585or 586 587 my $template = Template->new({ 588 PRE_DEFINE => { 589 title => 'A Demo Page', 590 author => 'Joe Random Hacker', 591 version => 3.14, 592 }, 593 }; 594 595=head2 CONSTANTS 596 597The C<CONSTANTS> option can be used to specify a hash array of template 598variables that are compile-time constants. These variables are 599resolved once when the template is compiled, and thus don't require 600further resolution at runtime. This results in significantly faster 601processing of the compiled templates and can be used for variables that 602don't change from one request to the next. 603 604 my $template = Template->new({ 605 CONSTANTS => { 606 title => 'A Demo Page', 607 author => 'Joe Random Hacker', 608 version => 3.14, 609 }, 610 }; 611 612=head2 CONSTANT_NAMESPACE 613 614Constant variables are accessed via the C<constants> namespace by 615default. 616 617 [% constants.title %] 618 619The C<CONSTANTS_NAMESPACE> option can be set to specify an alternate 620namespace. 621 622 my $template = Template->new({ 623 CONSTANTS => { 624 title => 'A Demo Page', 625 # ...etc... 626 }, 627 CONSTANTS_NAMESPACE => 'const', 628 }; 629 630In this case the constants would then be accessed as: 631 632 [% const.title %] 633 634=head2 NAMESPACE 635 636The constant folding mechanism described above is an example of a 637namespace handler. Namespace handlers can be defined to provide 638alternate parsing mechanisms for variables in different namespaces. 639 640Under the hood, the L<Template> module converts a constructor configuration 641such as: 642 643 my $template = Template->new({ 644 CONSTANTS => { 645 title => 'A Demo Page', 646 # ...etc... 647 }, 648 CONSTANTS_NAMESPACE => 'const', 649 }; 650 651into one like: 652 653 my $template = Template->new({ 654 NAMESPACE => { 655 const => Template:::Namespace::Constants->new({ 656 title => 'A Demo Page', 657 # ...etc... 658 }), 659 }, 660 }; 661 662You can use this mechanism to define multiple constant namespaces, or 663to install custom handlers of your own. 664 665 my $template = Template->new({ 666 NAMESPACE => { 667 site => Template:::Namespace::Constants->new({ 668 title => "Wardley's Widgets", 669 version => 2.718, 670 }), 671 author => Template:::Namespace::Constants->new({ 672 name => 'Andy Wardley', 673 email => 'abw@andywardley.com', 674 }), 675 voodoo => My::Namespace::Handler->new( ... ), 676 }, 677 }; 678 679Now you have two constant namespaces, for example: 680 681 [% site.title %] 682 [% author.name %] 683 684as well as your own custom namespace handler installed for the 'voodoo' 685namespace. 686 687 [% voodoo.magic %] 688 689See L<Template::Namespace::Constants> 690for an example of what a namespace handler looks like on the inside. 691 692=head1 Template Processing Options 693 694The following options are used to specify any additional templates that should 695be processed before, after, around or instead of the template passed as the 696first argument to the L<Template> L<process()|Template#process()> method. 697These options can be perform various useful tasks such as adding standard 698headers or footers to all pages, wrapping page output in other templates, 699pre-defining variables or performing initialisation or cleanup tasks, 700automatically generating page summary information, navigation elements, and so 701on. 702 703The task of processing the template is delegated internally to the 704L<Template::Service> module which, unsurprisingly, also has a 705L<process()|Template::Service#process()> method. Any templates defined by the 706C<PRE_PROCESS> option are processed first and any output generated is added to 707the output buffer. Then the main template is processed, or if one or more 708C<PROCESS> templates are defined then they are instead processed in turn. In this 709case, one of the C<PROCESS> templates is responsible for processing the main 710template, by a directive such as: 711 712 [% PROCESS $template %] 713 714The output of processing the main template or the C<PROCESS> template(s) 715is then wrapped in any C<WRAPPER> templates, if defined. C<WRAPPER> 716templates don't need to worry about explicitly processing the template 717because it will have been done for them already. Instead C<WRAPPER> 718templates access the content they are wrapping via the C<content> 719variable. 720 721 wrapper before 722 [% content %] 723 wrapper after 724 725This output generated from processing the main template, and/or any 726C<PROCESS> or C<WRAPPER> templates is added to the output buffer. Finally, 727any C<POST_PROCESS> templates are processed and their output is also 728added to the output buffer which is then returned. 729 730If the main template throws an exception during processing then any relevant 731template(s) defined via the C<ERROR> option will be processed instead. If 732defined and successfully processed, the output from the error template will be 733added to the output buffer in place of the template that generated the error 734and processing will continue, applying any C<WRAPPER> and C<POST_PROCESS> 735templates. If no relevant C<ERROR> option is defined, or if the error occurs 736in one of the C<PRE_PROCESS>, C<WRAPPER> or C<POST_PROCESS> templates, then 737the process will terminate immediately and the error will be returned. 738 739=head2 PRE_PROCESS, POST_PROCESS 740 741These values may be set to contain the name(s) of template files 742(relative to C<INCLUDE_PATH>) which should be processed immediately 743before and/or after each template. These do not get added to 744templates processed into a document via directives such as C<INCLUDE>, 745C<PROCESS>, C<WRAPPER> etc. 746 747 my $template = Template->new({ 748 PRE_PROCESS => 'header', 749 POST_PROCESS => 'footer', 750 }; 751 752Multiple templates may be specified as a reference to a list. Each is 753processed in the order defined. 754 755 my $template = Template->new({ 756 PRE_PROCESS => [ 'config', 'header' ], 757 POST_PROCESS => 'footer', 758 }; 759 760Alternately, multiple template may be specified as a single string, 761delimited by 'C<:>'. This delimiter string can be changed via the 762C<DELIMITER> option. 763 764 my $template = Template->new({ 765 PRE_PROCESS => 'config:header', 766 POST_PROCESS => 'footer', 767 }; 768 769The C<PRE_PROCESS> and C<POST_PROCESS> templates are evaluated in the same 770variable context as the main document and may define or update 771variables for subsequent use. 772 773config: 774 775 [% # set some site-wide variables 776 bgcolor = '#ffffff' 777 version = 2.718 778 %] 779 780header: 781 782 [% DEFAULT title = 'My Funky Web Site' %] 783 <html> 784 <head> 785 <title>[% title %]</title> 786 </head> 787 <body bgcolor="[% bgcolor %]"> 788 789footer: 790 791 <hr> 792 Version [% version %] 793 </body> 794 </html> 795 796The L<Template::Document> object representing the main template being processed 797is available within C<PRE_PROCESS> and C<POST_PROCESS> templates as the C<template> 798variable. Metadata items defined via the C<META> directive may be accessed 799accordingly. 800 801 $template->process('mydoc.html', $vars); 802 803mydoc.html: 804 805 [% META title = 'My Document Title' %] 806 blah blah blah 807 ... 808 809header: 810 811 <html> 812 <head> 813 <title>[% template.title %]</title> 814 </head> 815 <body bgcolor="[% bgcolor %]"> 816 817=head2 PROCESS 818 819The C<PROCESS> option may be set to contain the name(s) of template files 820(relative to C<INCLUDE_PATH>) which should be processed instead of the main 821template passed to the L<Template> L<process()|Template#process()> method. 822This can be used to apply consistent wrappers around all templates, similar to 823the use of C<PRE_PROCESS> and C<POST_PROCESS> templates. 824 825 my $template = Template->new({ 826 PROCESS => 'content', 827 }; 828 829 # processes 'content' instead of 'foo.html' 830 $template->process('foo.html'); 831 832A reference to the original template is available in the C<template> 833variable. Metadata items can be inspected and the template can be 834processed by specifying it as a variable reference (i.e. prefixed by 835C<$>) to an C<INCLUDE>, C<PROCESS> or C<WRAPPER> directive. 836 837content: 838 839 <html> 840 <head> 841 <title>[% template.title %]</title> 842 </head> 843 <body> 844 <!-- begin content --> 845 [% PROCESS $template %] 846 <!-- end content --> 847 <hr> 848 © Copyright [% template.copyright %] 849 </body> 850 </html> 851 852foo.html: 853 854 [% META 855 title = 'The Foo Page' 856 author = 'Fred Foo' 857 copyright = '2000 Fred Foo' 858 %] 859 <h1>[% template.title %]</h1> 860 Welcome to the Foo Page, blah blah blah 861 862output: 863 864 <html> 865 <head> 866 <title>The Foo Page</title> 867 </head> 868 <body> 869 <!-- begin content --> 870 <h1>The Foo Page</h1> 871 Welcome to the Foo Page, blah blah blah 872 <!-- end content --> 873 <hr> 874 © Copyright 2000 Fred Foo 875 </body> 876 </html> 877 878=head2 WRAPPER 879 880The C<WRAPPER> option can be used to specify one or more templates which 881should be used to wrap around the output of the main page template. 882The main template is processed first (or any C<PROCESS> template(s)) and 883the output generated is then passed as the C<content> variable to the 884C<WRAPPER> template(s) as they are processed. 885 886 my $template = Template->new({ 887 WRAPPER => 'wrapper', 888 }; 889 890 # process 'foo' then wrap in 'wrapper' 891 $template->process('foo', { message => 'Hello World!' }); 892 893wrapper: 894 895 <wrapper> 896 [% content %] 897 </wrapper> 898 899foo: 900 901 This is the foo file! 902 Message: [% message %] 903 904The output generated from this example is: 905 906 <wrapper> 907 This is the foo file! 908 Message: Hello World! 909 </wrapper> 910 911You can specify more than one C<WRAPPER> template by setting the value to 912be a reference to a list of templates. The C<WRAPPER> templates will be 913processed in reverse order with the output of each being passed to the 914next (or previous, depending on how you look at it) as the 'content' 915variable. It sounds complicated, but the end result is that it just 916"Does The Right Thing" to make wrapper templates nest in the order you 917specify. 918 919 my $template = Template->new({ 920 WRAPPER => [ 'outer', 'inner' ], 921 }; 922 923 # process 'foo' then wrap in 'inner', then in 'outer' 924 $template->process('foo', { message => 'Hello World!' }); 925 926outer: 927 928 <outer> 929 [% content %] 930 </outer> 931 932inner: 933 934 <inner> 935 [% content %] 936 </inner> 937 938The output generated is then: 939 940 <outer> 941 <inner> 942 This is the foo file! 943 Message: Hello World! 944 </inner> 945 </outer> 946 947One side-effect of the "inside-out" processing of the C<WRAPPER> 948configuration item (and also the C<WRAPPER> directive) is that any 949variables set in the template being wrapped will be visible to the 950template doing the wrapping, but not the other way around. 951 952You can use this to good effect in allowing page templates to set 953pre-defined values which are then used in the wrapper templates. For 954example, our main page template 'foo' might look like this: 955 956foo: 957 958 [% page = { 959 title = 'Foo Page' 960 subtitle = 'Everything There is to Know About Foo' 961 author = 'Frank Oliver Octagon' 962 } 963 %] 964 965 <p> 966 Welcome to the page that tells you everything about foo 967 blah blah blah... 968 </p> 969 970The C<foo> template is processed before the wrapper template meaning 971that the C<page> data structure will be defined for use in the wrapper 972template. 973 974wrapper: 975 976 <html> 977 <head> 978 <title>[% page.title %]</title> 979 </head> 980 <body> 981 <h1>[% page.title %]</h1> 982 <h2>[% page.subtitle %]</h1> 983 <h3>by [% page.author %]</h3> 984 [% content %] 985 </body> 986 </html> 987 988It achieves the same effect as defining C<META> items which are then 989accessed via the C<template> variable (which you are still free to 990use within C<WRAPPER> templates), but gives you more flexibility in 991the type and complexity of data that you can define. 992 993=head2 ERROR 994 995The C<ERROR> (or C<ERRORS> if you prefer) configuration item can be used to 996name a single template or specify a hash array mapping exception types 997to templates which should be used for error handling. If an uncaught 998exception is raised from within a template then the appropriate error 999template will instead be processed. 1000 1001If specified as a single value then that template will be processed 1002for all uncaught exceptions. 1003 1004 my $template = Template->new({ 1005 ERROR => 'error.html' 1006 }); 1007 1008If the C<ERROR> item is a hash reference the keys are assumed to be 1009exception types and the relevant template for a given exception will 1010be selected. A C<default> template may be provided for the general 1011case. Note that C<ERROR> can be pluralised to C<ERRORS> if you find 1012it more appropriate in this case. 1013 1014 my $template = Template->new({ 1015 ERRORS => { 1016 user => 'user/index.html', 1017 dbi => 'error/database', 1018 default => 'error/default', 1019 }, 1020 }); 1021 1022In this example, any C<user> exceptions thrown will cause the 1023F<user/index.html> template to be processed, C<dbi> errors are handled 1024by F<error/database> and all others by the F<error/default> template. 1025Any C<PRE_PROCESS> and/or C<POST_PROCESS> templates will also be applied 1026to these error templates. 1027 1028Note that exception types are hierarchical and a C<foo> handler will 1029catch all C<foo.*> errors (e.g. C<foo.bar>, C<foo.bar.baz>) if a more 1030specific handler isn't defined. Be sure to quote any exception types 1031that contain periods to prevent Perl concatenating them into a single 1032string (i.e. C<user.passwd> is parsed as C<'user'.'passwd'>). 1033 1034 my $template = Template->new({ 1035 ERROR => { 1036 'user.login' => 'user/login.html', 1037 'user.passwd' => 'user/badpasswd.html', 1038 'user' => 'user/index.html', 1039 'default' => 'error/default', 1040 }, 1041 }); 1042 1043In this example, any template processed by the C<$template> object, or 1044other templates or code called from within, can raise a C<user.login> 1045exception and have the service redirect to the F<user/login.html> 1046template. Similarly, a C<user.passwd> exception has a specific 1047handling template, F<user/badpasswd.html>, while all other C<user> or 1048C<user.*> exceptions cause a redirection to the F<user/index.html> page. 1049All other exception types are handled by F<error/default>. 1050 1051Exceptions can be raised in a template using the C<THROW> directive, 1052 1053 [% THROW user.login 'no user id: please login' %] 1054 1055or by calling the L<throw()|Template::Context#throw()> method on the 1056current L<Template::Context> object, 1057 1058 $context->throw('user.passwd', 'Incorrect Password'); 1059 $context->throw('Incorrect Password'); # type 'undef' 1060 1061or from Perl code by calling C<die()> with a L<Template::Exception> object, 1062 1063 die (Template::Exception->new('user.denied', 'Invalid User ID')); 1064 1065or by simply calling L<die()> with an error string. This is 1066automagically caught and converted to an exception of 'C<undef>' 1067type which can then be handled in the usual way. 1068 1069 die "I'm sorry Dave, I can't do that"; 1070 1071Note that the 'C<undef>' we're talking about here is a literal string 1072rather than Perl's C<undef> used to represent undefined values. 1073 1074=head1 Template Runtime Options 1075 1076=head2 EVAL_PERL 1077 1078This flag is used to indicate if C<PERL> and/or C<RAWPERL> blocks should be 1079evaluated. It is disabled by default and any C<PERL> or C<RAWPERL> blocks 1080encountered will raise exceptions of type 'C<perl>' with the message 1081'C<EVAL_PERL not set>'. Note however that any C<RAWPERL> blocks should 1082always contain valid Perl code, regardless of the C<EVAL_PERL> flag. The 1083parser will fail to compile templates that contain invalid Perl code 1084in C<RAWPERL> blocks and will throw a 'C<file>' exception. 1085 1086When using compiled templates (see 1087L<Caching and Compiling Options>), 1088the C<EVAL_PERL> has an affect when the template is compiled, and again 1089when the templates is subsequently processed, possibly in a different 1090context to the one that compiled it. 1091 1092If the C<EVAL_PERL> is set when a template is compiled, then all C<PERL> and 1093C<RAWPERL> blocks will be included in the compiled template. If the 1094C<EVAL_PERL> option isn't set, then Perl code will be generated which 1095B<always> throws a 'C<perl>' exception with the message 'C<EVAL_PERL not 1096set>' B<whenever> the compiled template code is run. 1097 1098Thus, you must have C<EVAL_PERL> set if you want your compiled templates 1099to include C<PERL> and C<RAWPERL> blocks. 1100 1101At some point in the future, using a different invocation of the 1102Template Toolkit, you may come to process such a pre-compiled 1103template. Assuming the C<EVAL_PERL> option was set at the time the 1104template was compiled, then the output of any C<RAWPERL> blocks will be 1105included in the compiled template and will get executed when the 1106template is processed. This will happen regardless of the runtime 1107C<EVAL_PERL> status. 1108 1109Regular C<PERL> blocks are a little more cautious, however. If the 1110C<EVAL_PERL> flag isn't set for the I<current> context, that is, the 1111one which is trying to process it, then it will throw the familiar 'C<perl>' 1112exception with the message, 'C<EVAL_PERL not set>'. 1113 1114Thus you can compile templates to include C<PERL> blocks, but optionally 1115disable them when you process them later. Note however that it is 1116possible for a C<PERL> block to contain a Perl "C<BEGIN { # some code }>" 1117block which will always get run regardless of the runtime C<EVAL_PERL> 1118status. Thus, if you set C<EVAL_PERL> when compiling templates, it is 1119assumed that you trust the templates to Do The Right Thing. Otherwise 1120you must accept the fact that there's no bulletproof way to prevent 1121any included code from trampling around in the living room of the 1122runtime environment, making a real nuisance of itself if it really 1123wants to. If you don't like the idea of such uninvited guests causing 1124a bother, then you can accept the default and keep C<EVAL_PERL> disabled. 1125 1126=head2 OUTPUT 1127 1128Default output location or handler. This may be specified as one of: 1129a file name (relative to C<OUTPUT_PATH>, if defined, or the current 1130working directory if not specified absolutely); a file handle 1131(e.g. C<GLOB> or L<IO::Handle>) opened for writing; a reference to a text 1132string to which the output is appended (the string isn't cleared); a 1133reference to a subroutine which is called, passing the output text as 1134an argument; as a reference to an array, onto which the content will be 1135C<push()>ed; or as a reference to any object that supports the C<print()> 1136method. This latter option includes the C<Apache::Request> object which 1137is passed as the argument to Apache/mod_perl handlers. 1138 1139example 1 (file name): 1140 1141 my $template = Template->new({ 1142 OUTPUT => "/tmp/foo", 1143 }); 1144 1145example 2 (text string): 1146 1147 my $output = ''; 1148 my $template = Template->new({ 1149 OUTPUT => \$output, 1150 }); 1151 1152example 3 (file handle): 1153 1154 open (TOUT, ">", $file) || die "$file: $!\n"; 1155 my $template = Template->new({ 1156 OUTPUT => \*TOUT, 1157 }); 1158 1159example 4 (subroutine): 1160 1161 sub output { my $out = shift; print "OUTPUT: $out" } 1162 my $template = Template->new({ 1163 OUTPUT => \&output, 1164 }); 1165 1166example 5 (array reference): 1167 1168 my $template = Template->new({ 1169 OUTPUT => \@output, 1170 }) 1171 1172example 6 (Apache/mod_perl handler): 1173 1174 sub handler { 1175 my $r = shift; 1176 my $t = Template->new({ 1177 OUTPUT => $r, 1178 }); 1179 ... 1180 } 1181 1182The default C<OUTPUT> location be overridden by passing a third parameter to 1183the L<Template> L<process()|Template#process()> method. This can be specified 1184as any of the above argument types. 1185 1186 $t->process($file, $vars, "/tmp/foo"); 1187 $t->process($file, $vars, \$output); 1188 $t->process($file, $vars, \*MYGLOB); 1189 $t->process($file, $vars, \@output); 1190 $t->process($file, $vars, $r); # Apache::Request 1191 ... 1192 1193=head2 OUTPUT_PATH 1194 1195The C<OUTPUT_PATH> allows a directory to be specified into which output 1196files should be written. An output file can be specified by the 1197C<OUTPUT> option, or passed by name as the third parameter to the 1198L<Template> L<process()|Template#process()> method. 1199 1200 my $template = Template->new({ 1201 INCLUDE_PATH => "/tmp/src", 1202 OUTPUT_PATH => "/tmp/dest", 1203 }); 1204 1205 my $vars = { 1206 ... 1207 }; 1208 1209 foreach my $file ('foo.html', 'bar.html') { 1210 $template->process($file, $vars, $file) 1211 || die $template->error(); 1212 } 1213 1214This example will read the input files F</tmp/src/foo.html> and 1215F</tmp/src/bar.html> and write the processed output to F</tmp/dest/foo.html> 1216and F</tmp/dest/bar.html>, respectively. 1217 1218=head2 STRICT 1219 1220By default the Template Toolkit will silently ignore the use of undefined 1221variables (a bad design decision that I regret). 1222 1223When the C<STRICT> option is set, the use of any undefined variables or 1224values will cause an exception to be throw. The exception will have a 1225C<type> of C<var.undefined> and a message of the form 1226"undefined variable: xxx". 1227 1228 my $template = Template->new( 1229 STRICT => 1 1230 ); 1231 1232=head2 DEBUG 1233 1234The C<DEBUG> option can be used to enable debugging within the various 1235different modules that comprise the Template Toolkit. The 1236L<Template::Constants> module defines a set of 1237C<DEBUG_XXXX> constants which can be combined using the logical OR 1238operator, 'C<|>'. 1239 1240 use Template::Constants qw( :debug ); 1241 1242 my $template = Template->new({ 1243 DEBUG => DEBUG_PARSER | DEBUG_PROVIDER, 1244 }); 1245 1246For convenience, you can also provide a string containing a list 1247of lower case debug options, separated by any non-word characters. 1248 1249 my $template = Template->new({ 1250 DEBUG => 'parser, provider', 1251 }); 1252 1253The following C<DEBUG_XXXX> flags can be used: 1254 1255=over 4 1256 1257=item DEBUG_SERVICE 1258 1259Enables general debugging messages for the 1260L<Template::Service> module. 1261 1262=item DEBUG_CONTEXT 1263 1264Enables general debugging messages for the 1265L<Template::Context> module. 1266 1267=item DEBUG_PROVIDER 1268 1269Enables general debugging messages for the 1270L<Template::Provider> module. 1271 1272=item DEBUG_PLUGINS 1273 1274Enables general debugging messages for the 1275L<Template::Plugins> module. 1276 1277=item DEBUG_FILTERS 1278 1279Enables general debugging messages for the 1280L<Template::Filters> module. 1281 1282=item DEBUG_PARSER 1283 1284This flag causes the L<Template::Parser> to generate 1285debugging messages that show the Perl code generated by parsing and 1286compiling each template. 1287 1288=item DEBUG_UNDEF 1289 1290This option causes the Template Toolkit to throw an 'C<undef>' error 1291whenever it encounters an undefined variable value. 1292 1293=item DEBUG_DIRS 1294 1295This option causes the Template Toolkit to generate comments 1296indicating the source file, line and original text of each directive 1297in the template. These comments are embedded in the template output 1298using the format defined in the C<DEBUG_FORMAT> configuration item, or a 1299simple default format if unspecified. 1300 1301For example, the following template fragment: 1302 1303 Hello World 1304 1305would generate this output: 1306 1307 ## input text line 1 : ## 1308 Hello 1309 ## input text line 2 : World ## 1310 World 1311 1312=item DEBUG_ALL 1313 1314Enables all debugging messages. 1315 1316=item DEBUG_CALLER 1317 1318This option causes all debug messages that aren't newline terminated 1319to have the file name and line number of the caller appended to them. 1320 1321=back 1322 1323=head2 DEBUG_FORMAT 1324 1325The C<DEBUG_FORMAT> option can be used to specify a format string for the 1326debugging messages generated via the C<DEBUG_DIRS> option described 1327above. Any occurrences of C<$file>, C<$line> or C<$text> will be 1328replaced with the current file name, line or directive text, 1329respectively. Notice how the format is single quoted to prevent Perl 1330from interpolating those tokens as variables. 1331 1332 my $template = Template->new({ 1333 DEBUG => 'dirs', 1334 DEBUG_FORMAT => '<!-- $file line $line : [% $text %] -->', 1335 }); 1336 1337The following template fragment: 1338 1339 [% foo = 'World' %] 1340 Hello [% foo %] 1341 1342would then generate this output: 1343 1344 <!-- input text line 2 : [% foo = 'World' %] --> 1345 Hello <!-- input text line 3 : [% foo %] -->World 1346 1347The DEBUG directive can also be used to set a debug format within 1348a template. 1349 1350 [% DEBUG format '<!-- $file line $line : [% $text %] -->' %] 1351 1352=head1 Caching and Compiling Options 1353 1354=head2 CACHE_SIZE 1355 1356The L<Template::Provider> module caches compiled templates to avoid the need 1357to re-parse template files or blocks each time they are used. The C<CACHE_SIZE> 1358option is used to limit the number of compiled templates that the module 1359should cache. 1360 1361By default, the C<CACHE_SIZE> is undefined and all compiled templates are 1362cached. When set to any positive value, the cache will be limited to 1363storing no more than that number of compiled templates. When a new 1364template is loaded and compiled and the cache is full (i.e. the number 1365of entries == C<CACHE_SIZE>), the least recently used compiled template 1366is discarded to make room for the new one. 1367 1368The C<CACHE_SIZE> can be set to C<0> to disable caching altogether. 1369 1370 my $template = Template->new({ 1371 CACHE_SIZE => 64, # only cache 64 compiled templates 1372 }); 1373 1374 my $template = Template->new({ 1375 CACHE_SIZE => 0, # don't cache any compiled templates 1376 }); 1377 1378As well as caching templates as they are found, the L<Template::Provider> 1379also implements negative caching to keep track of templates that are 1380I<not> found. This allows the provider to quickly decline a request 1381for a template that it has previously failed to locate, saving the effort 1382of going to look for it again. This is useful when an C<INCLUDE_PATH> includes 1383multiple providers, ensuring that the request is passed down through the 1384providers as quickly as possible. 1385 1386=head2 STAT_TTL 1387 1388This value can be set to control how long the L<Template::Provider> will keep a 1389template cached in memory before checking to see if the source template has 1390changed. 1391 1392 my $provider = Template::Provider->new({ 1393 STAT_TTL => 60, # one minute 1394 }); 1395 1396The default value is 1 (second). You'll probably want to set this to a higher 1397value if you're running the Template Toolkit inside a persistent web server 1398application (e.g. mod_perl). For example, set it to 60 and the provider will 1399only look for changes to templates once a minute at most. However, during 1400development (or any time you're making frequent changes to templates) you'll 1401probably want to keep it set to a low value so that you don't have to wait 1402for the provider to notice that your templates have changed. 1403 1404=head2 COMPILE_EXT 1405 1406From version 2 onwards, the Template Toolkit has the ability to 1407compile templates to Perl code and save them to disk for subsequent 1408use (i.e. cache persistence). The C<COMPILE_EXT> option may be 1409provided to specify a filename extension for compiled template files. 1410It is undefined by default and no attempt will be made to read or write 1411any compiled template files. 1412 1413 my $template = Template->new({ 1414 COMPILE_EXT => '.ttc', 1415 }); 1416 1417If C<COMPILE_EXT> is defined (and C<COMPILE_DIR> isn't, see below) then compiled 1418template files with the C<COMPILE_EXT> extension will be written to the same 1419directory from which the source template files were loaded. 1420 1421Compiling and subsequent reuse of templates happens automatically 1422whenever the C<COMPILE_EXT> or C<COMPILE_DIR> options are set. The Template 1423Toolkit will automatically reload and reuse compiled files when it 1424finds them on disk. If the corresponding source file has been modified 1425since the compiled version as written, then it will load and re-compile 1426the source and write a new compiled version to disk. 1427 1428This form of cache persistence offers significant benefits in terms of 1429time and resources required to reload templates. Compiled templates can 1430be reloaded by a simple call to Perl's C<require()>, leaving Perl to handle 1431all the parsing and compilation. This is a Good Thing. 1432 1433=head2 COMPILE_DIR 1434 1435The C<COMPILE_DIR> option is used to specify an alternate directory root 1436under which compiled template files should be saved. 1437 1438 my $template = Template->new({ 1439 COMPILE_DIR => '/tmp/ttc', 1440 }); 1441 1442The C<COMPILE_EXT> option may also be specified to have a consistent file 1443extension added to these files. 1444 1445 my $template1 = Template->new({ 1446 COMPILE_DIR => '/tmp/ttc', 1447 COMPILE_EXT => '.ttc1', 1448 }); 1449 1450 my $template2 = Template->new({ 1451 COMPILE_DIR => '/tmp/ttc', 1452 COMPILE_EXT => '.ttc2', 1453 }); 1454 1455When C<COMPILE_EXT> is undefined, the compiled template files have the 1456same name as the original template files, but reside in a different 1457directory tree. 1458 1459Each directory in the C<INCLUDE_PATH> is replicated in full beneath the 1460C<COMPILE_DIR> directory. This example: 1461 1462 my $template = Template->new({ 1463 COMPILE_DIR => '/tmp/ttc', 1464 INCLUDE_PATH => '/home/abw/templates:/usr/share/templates', 1465 }); 1466 1467would create the following directory structure: 1468 1469 /tmp/ttc/home/abw/templates/ 1470 /tmp/ttc/usr/share/templates/ 1471 1472Files loaded from different C<INCLUDE_PATH> directories will have their 1473compiled forms save in the relevant C<COMPILE_DIR> directory. 1474 1475On Win32 platforms a filename may by prefixed by a drive letter and 1476colon. e.g. 1477 1478 C:/My Templates/header 1479 1480The colon will be silently stripped from the filename when it is added 1481to the C<COMPILE_DIR> value(s) to prevent illegal filename being generated. 1482Any colon in C<COMPILE_DIR> elements will be left intact. For example: 1483 1484 # Win32 only 1485 my $template = Template->new({ 1486 DELIMITER => ';', 1487 COMPILE_DIR => 'C:/TT2/Cache', 1488 INCLUDE_PATH => 'C:/TT2/Templates;D:/My Templates', 1489 }); 1490 1491This would create the following cache directories: 1492 1493 C:/TT2/Cache/C/TT2/Templates 1494 C:/TT2/Cache/D/My Templates 1495 1496=head1 Plugins and Filters 1497 1498=head2 PLUGINS 1499 1500The C<PLUGINS> options can be used to provide a reference to a hash array 1501that maps plugin names to Perl module names. A number of standard 1502plugins are defined (e.g. C<table>, C<format>, C<cgi>, etc.) which map to 1503their corresponding C<Template::Plugin::*> counterparts. These can be 1504redefined by values in the C<PLUGINS> hash. 1505 1506 my $template = Template->new({ 1507 PLUGINS => { 1508 cgi => 'MyOrg::Template::Plugin::CGI', 1509 foo => 'MyOrg::Template::Plugin::Foo', 1510 bar => 'MyOrg::Template::Plugin::Bar', 1511 }, 1512 }); 1513 1514The recommended convention is to specify these plugin names in lower 1515case. The Template Toolkit first looks for an exact case-sensitive 1516match and then tries the lower case conversion of the name specified. 1517 1518 [% USE Foo %] # look for 'Foo' then 'foo' 1519 1520If you define all your C<PLUGINS> with lower case names then they will be 1521located regardless of how the user specifies the name in the USE 1522directive. If, on the other hand, you define your C<PLUGINS> with upper 1523or mixed case names then the name specified in the C<USE> directive must 1524match the case exactly. 1525 1526The C<USE> directive is used to create plugin objects and does so by calling 1527the L<plugin()|Template::Context#plugin()> method on the current 1528L<Template::Context> object. If the plugin name is defined in the C<PLUGINS> 1529hash then the corresponding Perl module is loaded via C<require()>. The 1530context then calls the L<load()|Template::Plugin#load()> class method which 1531should return the class name (default and general case) or a prototype object 1532against which the L<new()|Template::Plugin#new()> method can be called to 1533instantiate individual plugin objects. 1534 1535If the plugin name is not defined in the C<PLUGINS> hash then the 1536C<PLUGIN_BASE> and/or C<LOAD_PERL> options come into effect. 1537 1538=head2 PLUGIN_BASE 1539 1540If a plugin is not defined in the C<PLUGINS> hash then the C<PLUGIN_BASE> is used 1541to attempt to construct a correct Perl module name which can be successfully 1542loaded. 1543 1544The C<PLUGIN_BASE> can be specified as a reference to an array of module 1545namespaces, or as a single value which is automatically converted to a 1546list. The default C<PLUGIN_BASE> value (C<Template::Plugin>) is then added 1547to the end of this list. 1548 1549example 1: 1550 1551 my $template = Template->new({ 1552 PLUGIN_BASE => 'MyOrg::Template::Plugin', 1553 }); 1554 1555 [% USE Foo %] # => MyOrg::Template::Plugin::Foo 1556 or Template::Plugin::Foo 1557 1558example 2: 1559 1560 my $template = Template->new({ 1561 PLUGIN_BASE => [ 'MyOrg::Template::Plugin', 1562 'YourOrg::Template::Plugin' ], 1563 }); 1564 1565template: 1566 1567 [% USE Foo %] # => MyOrg::Template::Plugin::Foo 1568 or YourOrg::Template::Plugin::Foo 1569 or Template::Plugin::Foo 1570 1571If you don't want the default C<Template::Plugin> namespace added to the 1572end of the C<PLUGIN_BASE>, then set the C<$Template::Plugins::PLUGIN_BASE> 1573variable to a false value before calling the L<new()|Template> L<Template#new()> 1574constructor method. This is shown in the example below where the 1575C<Foo> plugin is located as C<My::Plugin::Foo> or C<Your::Plugin::Foo> but not 1576as C<Template::Plugin::Foo>. 1577 1578example 3: 1579 1580 use Template::Plugins; 1581 $Template::Plugins::PLUGIN_BASE = ''; 1582 1583 my $template = Template->new({ 1584 PLUGIN_BASE => [ 'My::Plugin', 1585 'Your::Plugin' ], 1586 }); 1587 1588template: 1589 1590 [% USE Foo %] # => My::Plugin::Foo 1591 or Your::Plugin::Foo 1592 1593=head2 LOAD_PERL 1594 1595If a plugin cannot be loaded using the C<PLUGINS> or C<PLUGIN_BASE> 1596approaches then the provider can make a final attempt to load the 1597module without prepending any prefix to the module path. This allows 1598regular Perl modules (i.e. those that don't reside in the 1599L<Template::Plugin> or some other such namespace) to be loaded and used 1600as plugins. 1601 1602By default, the C<LOAD_PERL> option is set to C<0> and no attempt will be made 1603to load any Perl modules that aren't named explicitly in the C<PLUGINS> 1604hash or reside in a package as named by one of the C<PLUGIN_BASE> 1605components. 1606 1607Plugins loaded using the C<PLUGINS> or C<PLUGIN_BASE> receive a reference to 1608the current context object as the first argument to the 1609L<new()|Template::Plugin#new()> constructor. Modules loaded using C<LOAD_PERL> 1610are assumed to not conform to the plugin interface. They must provide a C<new()> 1611class method for instantiating objects but it will not receive a reference to 1612the context as the first argument. 1613 1614Plugin modules should provide a L<load()|Template::Plugin#load()> class method 1615(or inherit the default one from the L<Template::Plugin> base class) which is 1616called the first time the plugin is loaded. Regular Perl modules need not. In 1617all other respects, regular Perl objects and Template Toolkit plugins are 1618identical. 1619 1620If a particular Perl module does not conform to the common, but not 1621unilateral, C<new()> constructor convention then a simple plugin wrapper 1622can be written to interface to it. 1623 1624=head2 FILTERS 1625 1626The C<FILTERS> option can be used to specify custom filters which can 1627then be used with the C<FILTER> directive like any other. These are 1628added to the standard filters which are available by default. Filters 1629specified via this option will mask any standard filters of the same 1630name. 1631 1632The C<FILTERS> option should be specified as a reference to a hash array 1633in which each key represents the name of a filter. The corresponding 1634value should contain a reference to an array containing a subroutine 1635reference and a flag which indicates if the filter is static (C<0>) or 1636dynamic (C<1>). A filter may also be specified as a solitary subroutine 1637reference and is assumed to be static. 1638 1639 $template = Template->new({ 1640 FILTERS => { 1641 'sfilt1' => \&static_filter, # static 1642 'sfilt2' => [ \&static_filter, 0 ], # same as above 1643 'dfilt1' => [ \&dyanamic_filter_factory, 1 ], 1644 }, 1645 }); 1646 1647Additional filters can be specified at any time by calling the 1648L<define_filter()|Template::Context#define_filter()> method on the current 1649L<Template::Context> object. The method accepts a filter name, a reference to a 1650filter subroutine and an optional flag to indicate if the filter is dynamic. 1651 1652 my $context = $template->context(); 1653 $context->define_filter('new_html', \&new_html); 1654 $context->define_filter('new_repeat', \&new_repeat, 1); 1655 1656Static filters are those where a single subroutine reference is used 1657for all invocations of a particular filter. Filters that don't accept 1658any configuration parameters (e.g. C<html>) can be implemented 1659statically. The subroutine reference is simply returned when that 1660particular filter is requested. The subroutine is called to filter 1661the output of a template block which is passed as the only argument. 1662The subroutine should return the modified text. 1663 1664 sub static_filter { 1665 my $text = shift; 1666 # do something to modify $text... 1667 return $text; 1668 } 1669 1670The following template fragment: 1671 1672 [% FILTER sfilt1 %] 1673 Blah blah blah. 1674 [% END %] 1675 1676is approximately equivalent to: 1677 1678 &static_filter("\nBlah blah blah.\n"); 1679 1680Filters that can accept parameters (e.g. C<truncate>) should be 1681implemented dynamically. In this case, the subroutine is taken to be 1682a filter 'factory' that is called to create a unique filter subroutine 1683each time one is requested. A reference to the current 1684L<Template::Context> object is passed as the first parameter, followed by 1685any additional parameters specified. The subroutine should return 1686another subroutine reference (usually a closure) which implements the 1687filter. 1688 1689 sub dynamic_filter_factory { 1690 my ($context, @args) = @_; 1691 1692 return sub { 1693 my $text = shift; 1694 # do something to modify $text... 1695 return $text; 1696 } 1697 } 1698 1699The following template fragment: 1700 1701 [% FILTER dfilt1(123, 456) %] 1702 Blah blah blah 1703 [% END %] 1704 1705is approximately equivalent to: 1706 1707 my $filter = &dynamic_filter_factory($context, 123, 456); 1708 &$filter("\nBlah blah blah.\n"); 1709 1710See the C<FILTER> directive for further examples. 1711 1712=head1 Customisation and Extension 1713 1714=head2 LOAD_TEMPLATES 1715 1716The C<LOAD_TEMPLATES> option can be used to provide a reference to a list 1717of L<Template::Provider> objects or sub-classes thereof which will take 1718responsibility for loading and compiling templates. 1719 1720 my $template = Template->new({ 1721 LOAD_TEMPLATES => [ 1722 MyOrg::Template::Provider->new({ ... }), 1723 Template::Provider->new({ ... }), 1724 ], 1725 }); 1726 1727When a C<PROCESS>, C<INCLUDE> or C<WRAPPER> directive is encountered, the 1728named template may refer to a locally defined C<BLOCK> or a file relative to 1729the C<INCLUDE_PATH> (or an absolute or relative path if the appropriate 1730C<ABSOLUTE> or C<RELATIVE> options are set). If a C<BLOCK> definition can't be 1731found (see the L<Template::Context> L<template()|Template::Context#template()> 1732method for a discussion of C<BLOCK> locality) then each of the 1733C<LOAD_TEMPLATES> provider objects is queried in turn via the 1734L<fetch()|Template::Provider#fetch()> method to see if it can supply the 1735required template. 1736 1737Each provider can return a compiled template, an error, or decline to service 1738the request in which case the responsibility is passed to the next provider. 1739If none of the providers can service the request then a 'not found' error is 1740returned. The same basic provider mechanism is also used for the C<INSERT> 1741directive but it bypasses any C<BLOCK> definitions and doesn't attempt is to 1742parse or process the contents of the template file. 1743 1744If C<LOAD_TEMPLATES> is undefined, a single default provider will be 1745instantiated using the current configuration parameters. For example, the 1746L<Template::Provider> C<INCLUDE_PATH> option can be specified in the L<Template> 1747configuration and will be correctly passed to the provider's constructor 1748method. 1749 1750 my $template = Template->new({ 1751 INCLUDE_PATH => '/here:/there', 1752 }); 1753 1754=head2 LOAD_PLUGINS 1755 1756The C<LOAD_PLUGINS> options can be used to specify a list of provider objects 1757(i.e. they implement the L<fetch()|Template::Plugins#fetch()> method) which 1758are responsible for loading and instantiating template plugin objects. The 1759L<Template::Context> L<plugin()|Template::Context#plugin()> method queries 1760each provider in turn in a "Chain of Responsibility" as per the 1761L<template()|Template::Context#template()> and 1762L<filter()|Template::Context#filter()> methods. 1763 1764 my $template = Template->new({ 1765 LOAD_PLUGINS => [ 1766 MyOrg::Template::Plugins->new({ ... }), 1767 Template::Plugins->new({ ... }), 1768 ], 1769 }); 1770 1771By default, a single L<Template::Plugins> object is created using the 1772current configuration hash. Configuration items destined for the 1773L<Template::Plugins> constructor may be added to the Template 1774constructor. 1775 1776 my $template = Template->new({ 1777 PLUGIN_BASE => 'MyOrg::Template::Plugins', 1778 LOAD_PERL => 1, 1779 }); 1780 1781=head2 LOAD_FILTERS 1782 1783The C<LOAD_FILTERS> option can be used to specify a list of provider objects 1784(i.e. they implement the L<fetch()|Template::Filters#fetch()> method) which 1785are responsible for returning and/or creating filter subroutines. The 1786L<Template::Context> L<filter()|Template::Context#filter()> method queries 1787each provider in turn in a "Chain of Responsibility" as per the 1788L<template()|Template::Context#template()> and 1789L<plugin()|Template::Context#plugin()> methods. 1790 1791 my $template = Template->new({ 1792 LOAD_FILTERS => [ 1793 MyTemplate::Filters->new(), 1794 Template::Filters->new(), 1795 ], 1796 }); 1797 1798By default, a single L<Template::Filters> object is created for the 1799C<LOAD_FILTERS> list. 1800 1801=head2 TOLERANT 1802 1803The C<TOLERANT> flag is used by the various Template Toolkit provider modules 1804(L<Template::Provider>, L<Template::Plugins>, L<Template::Filters>) to control 1805their behaviour when errors are encountered. By default, any errors are 1806reported as such, with the request for the particular resource (C<template>, 1807C<plugin>, C<filter>) being denied and an exception raised. 1808 1809When the C<TOLERANT> flag is set to any true values, errors will be silently 1810ignored and the provider will instead return C<STATUS_DECLINED>. This allows a 1811subsequent provider to take responsibility for providing the resource, rather 1812than failing the request outright. If all providers decline to service the 1813request, either through tolerated failure or a genuine disinclination to 1814comply, then a 'C<E<lt>resourceE<gt> not found>' exception is raised. 1815 1816=head2 SERVICE 1817 1818A reference to a L<Template::Service> object, or sub-class thereof, to which 1819the L<Template> module should delegate. If unspecified, a L<Template::Service> 1820object is automatically created using the current configuration hash. 1821 1822 my $template = Template->new({ 1823 SERVICE => MyOrg::Template::Service->new({ ... }), 1824 }); 1825 1826=head2 CONTEXT 1827 1828A reference to a L<Template::Context> object which is used to define a 1829specific environment in which template are processed. A L<Template::Context> 1830object is passed as the only parameter to the Perl subroutines that represent 1831"compiled" template documents. Template subroutines make callbacks into the 1832context object to access Template Toolkit functionality, for example, to 1833C<INCLUDE> or C<PROCESS> another template 1834(L<include()|Template::Context#include()> and 1835L<process()|Template::Context#process()> methods, respectively), to C<USE> a 1836plugin (L<plugin()|Template::Context#plugin()>) or instantiate a filter 1837(L<filter()|Template::Context#filter()>) or to access the stash 1838(L<stash()|Template::Context#stash()>) which manages variable definitions via 1839the L<get()|Template::Stash#get()> and L<set()|Template::Stash#set()> methods. 1840 1841 my $template = Template->new({ 1842 CONTEXT => MyOrg::Template::Context->new({ ... }), 1843 }); 1844 1845=head2 STASH 1846 1847A reference to a L<Template::Stash> object or sub-class which will take 1848responsibility for managing template variables. 1849 1850 my $stash = MyOrg::Template::Stash->new({ ... }); 1851 my $template = Template->new({ 1852 STASH => $stash, 1853 }); 1854 1855If unspecified, a default stash object is created using the C<VARIABLES> 1856configuration item to initialise the stash variables. 1857 1858 my $template = Template->new({ 1859 VARIABLES => { 1860 id => 'abw', 1861 name => 'Andy Wardley', 1862 }, 1863 }; 1864 1865=head2 PARSER 1866 1867The L<Template::Parser> module implements a parser object for compiling 1868templates into Perl code which can then be executed. A default object 1869of this class is created automatically and then used by the 1870L<Template::Provider> whenever a template is loaded and requires 1871compilation. The C<PARSER> option can be used to provide a reference to 1872an alternate parser object. 1873 1874 my $template = Template->new({ 1875 PARSER => MyOrg::Template::Parser->new({ ... }), 1876 }); 1877 1878=head2 GRAMMAR 1879 1880The C<GRAMMAR> configuration item can be used to specify an alternate 1881grammar for the parser. This allows a modified or entirely new 1882template language to be constructed and used by the Template Toolkit. 1883 1884Source templates are compiled to Perl code by the L<Template::Parser> 1885using the L<Template::Grammar> (by default) to define the language 1886structure and semantics. Compiled templates are thus inherently 1887"compatible" with each other and there is nothing to prevent any 1888number of different template languages being compiled and used within 1889the same Template Toolkit processing environment (other than the usual 1890time and memory constraints). 1891 1892The L<Template::Grammar> file is constructed from a YACC like grammar 1893(using C<Parse::YAPP>) and a skeleton module template. These files are 1894provided, along with a small script to rebuild the grammar, in the 1895F<parser> sub-directory of the distribution. 1896 1897You don't have to know or worry about these unless you want to hack on the 1898template language or define your own variant. There is a F<README> file in the 1899same directory which provides some small guidance but it is assumed that you 1900know what you're doing if you venture herein. If you grok LALR parsers, then 1901you should find it comfortably familiar. 1902 1903By default, an instance of the default L<Template::Grammar> will be 1904created and used automatically if a C<GRAMMAR> item isn't specified. 1905 1906 use MyOrg::Template::Grammar; 1907 1908 my $template = Template->new({ 1909 GRAMMAR = MyOrg::Template::Grammar->new(); 1910 }); 1911 1912=cut 1913 1914# Local Variables: 1915# mode: perl 1916# perl-indent-level: 4 1917# indent-tabs-mode: nil 1918# End: 1919# 1920# vim: expandtab shiftwidth=4: 1921