home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Variables.pod < prev    next >
Encoding:
Text File  |  2004-01-30  |  23.8 KB  |  869 lines

  1. #============================================================= -*-perl-*-
  2. #
  3. # Template::Manual::Variables
  4. #
  5. # DESCRIPTION
  6. #   This section describes the different ways in which Perl data can be
  7. #   bound to template variables and accessed via Template Toolkit
  8. #   directives.
  9. #
  10. # AUTHOR
  11. #   Andy Wardley  <abw@andywardley.com>
  12. #
  13. # COPYRIGHT
  14. #   Copyright (C) 1996-2001 Andy Wardley.  All Rights Reserved.
  15. #   Copyright (C) 1998-2001 Canon Research Centre Europe Ltd.
  16. #
  17. #   This module is free software; you can redistribute it and/or
  18. #   modify it under the same terms as Perl itself.
  19. #
  20. # REVISION
  21. #   
  22. #
  23. #========================================================================
  24.  
  25.  
  26. #------------------------------------------------------------------------
  27. # IMPORTANT NOTE
  28. #   This documentation is generated automatically from source
  29. #   templates.  Any changes you make here may be lost.
  30. #   The 'docsrc' documentation source bundle is available for download
  31. #   from http://www.template-toolkit.org/docs.html and contains all
  32. #   the source templates, XML files, scripts, etc., from which the
  33. #   documentation for the Template Toolkit is built.
  34. #------------------------------------------------------------------------
  35.  
  36. =head1 NAME
  37.  
  38. Template::Manual::Variables - Template variables and code bindings
  39.  
  40. =head1 DESCRIPTION
  41.  
  42. This section describes the different ways in which Perl data can be
  43. bound to template variables and accessed via Template Toolkit
  44. directives.
  45.  
  46. =head2 Template Variables
  47.  
  48. A reference to a hash array may be passed as the second argument to
  49. the process() method, containing definitions of template variables.
  50. The VARIABLES (a.k.a. PRE_DEFINE) option can also be used to pre-define
  51. variables for all templates processed by the object.
  52.  
  53.     my $tt = Template->new({
  54.     VARIABLES => {
  55.         version => 3.14,
  56.         release => 'Sahara',
  57.     },
  58.     });
  59.  
  60.     my $vars = {
  61.     serial_no => 271828,
  62.     };
  63.  
  64.     $tt->process('myfile', $vars);
  65.  
  66. 'myfile':
  67.  
  68.     This is version [% version %] ([% release %]).
  69.     Serial number: [% serial_no %]
  70.  
  71. output: 
  72.  
  73.     This is version 3.14 (Sahara)
  74.     Serial number: 271828
  75.  
  76. Variable names may contain any alphanumeric characters or underscores.
  77. They may be lower, upper or mixed case although the usual convention
  78. is to use lower case.  The case I<is> significant however, and 'foo',
  79. 'Foo' and 'FOO' are all different variables.  Upper case variable
  80. names are permitted, but not recommended due to a possible conflict
  81. with an existing or future reserved word.  As of version 2.00, these
  82. are:
  83.  
  84.         GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER 
  85.     IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
  86.     USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
  87.     TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP 
  88.     CLEAR TO STEP AND OR NOT MOD DIV END
  89.  
  90.  
  91. The variable values may be of virtually any Perl type, including
  92. simple scalars, references to lists, hash arrays, subroutines or
  93. objects.  The Template Toolkit will automatically apply the correct
  94. procedure to accessing these values as they are used in the template.
  95.  
  96. Example:
  97.  
  98.     my $vars = {
  99.     article => 'The Third Shoe',
  100.     person  => { 
  101.         id    => 314, 
  102.         name  => 'Mr. Blue',
  103.         email => 'blue@nowhere.org',
  104.     },
  105.     primes  => [ 2, 3, 5, 7, 11, 13 ],
  106.     wizard  => sub { return join(' ', 'Abracadabra!', @_) },
  107.     cgi     => CGI->new('mode=submit&debug=1'),
  108.     };
  109.  
  110. template:
  111.  
  112.     [% article %]
  113.  
  114.     [% person.id %]: [% person.name %] <[% person.email %]>
  115.  
  116.     [% primes.first %] - [% primes.last %], including [% primes.3 %]
  117.     [% primes.size %] prime numbers: [% primes.join(', ') %]
  118.  
  119.     [% wizard %]
  120.     [% wizard('Hocus Pocus!') %]
  121.  
  122.     [% cgi.param('mode') %]
  123.  
  124. output:
  125.  
  126.     The Third Shoe
  127.  
  128.     314: Mr. Blue <blue@nowhere.org>
  129.  
  130.     2 - 13, including 7
  131.     6 prime numbers: 2, 3, 5, 7, 11, 13
  132.  
  133.     Abracadabra!
  134.     Abracadabra! Hocus Pocus!
  135.     
  136.     submit
  137.  
  138. =head2 Scalar Values
  139.  
  140. Regular scalar variables are accessed by simply specifying their name.
  141. As these are just entries in the top-level variable hash they can be 
  142. considered special cases of hash array referencing as described below,
  143. with the main namespace hash automatically implied.
  144.  
  145.     [% article %]
  146.  
  147. =head2 Hash Array References
  148.  
  149. Members of hash arrays are accessed by specifying the hash reference
  150. and key separated by the dot '.' operator.
  151.  
  152.     my $vars = {
  153.       'home' => 'http://www.myserver.com/homepage.html',
  154.       'page' => {
  155.           'this' => 'mypage.html',
  156.           'next' => 'nextpage.html',
  157.           'prev' => 'prevpage.html',
  158.       },
  159.     };
  160.  
  161. template:
  162.  
  163.     <a href="[% home %]">Home</a>
  164.     <a href="[% page.prev %]">Previous Page</a>
  165.     <a href="[% page.next %]">Next Page</a>
  166.  
  167. output:
  168.  
  169.     <a href="http://www.myserver.com/homepage.html">Home</a>
  170.     <a href="prevpage.html">Previous Page</a>
  171.     <a href="nextpage.html">Next Page</a>
  172.  
  173. Any key in a hash which starts with a '_' or '.' character will be
  174. considered private and cannot be evaluated or updated from within a
  175. template.  The undefined value will be returned for any such variable
  176. accessed which the Template Toolkit will silently ignore (unless the
  177. DEBUG option is enabled).
  178.  
  179.     my $vars = {
  180.     message => 'Hello World!',
  181.     _secret => "On the Internet, no-one knows you're a dog",
  182.     thing   => {
  183.          public  => 123,
  184.         _private => 456,
  185.        '.hidden' => 789,
  186.     },
  187.     };
  188.  
  189. template:
  190.  
  191.     [% message %]        # outputs "Hello World!"
  192.     [% _secret %]               # no output
  193.     [% thing.public %]          # outputs "123"
  194.     [% thing._private %]        # no output
  195.     [% thing..hidden %]         # ERROR: unexpected token (..)
  196.  
  197. To access a hash entry using a key stored in another variable, prefix
  198. the key variable with '$' to have it interpolated before use (see
  199. L<Variable Interpolation>).
  200.  
  201.     [% pagename = 'next' %]
  202.     [% page.$pagename %]       # same as [% page.next %]
  203.  
  204. When you assign to a variable that contains multiple namespace 
  205. elements (i.e. it has one or more '.' characters in the name),
  206. any hashes required to represent intermediate namespaces will be 
  207. created automatically.  In this following example, the 'product' 
  208. variable automatically springs into life as a hash array unless
  209. otherwise defined.
  210.  
  211.     [% product.id    = 'XYZ-2000' 
  212.        product.desc  = 'Bogon Generator'
  213.        product.price = 666 
  214.     %]
  215.    
  216.     The [% product.id %] [% product.desc %] 
  217.     costs $[% product.price %].00
  218.  
  219. output:
  220.  
  221.     The XYZ-2000 Bogon Generator 
  222.     costs $666.00
  223.  
  224. You can use Perl's familiar '{' ... '}' construct to explicitly create
  225. a hash and assign it to a variable.  Note that commas are optional
  226. between key/value pairs and '=' can be used in place of '=E<gt>'.
  227.  
  228.     [% product = {
  229.        id    => 'XYZ-2000',
  230.        desc  => 'Bogon Generator',
  231.        price => 666,
  232.        }
  233.     %]
  234.  
  235. =head2 List References
  236.  
  237. Items in lists are also accessed by use of the dot operator.
  238.  
  239.     my $vars = {
  240.       'people' => [ 'Tom', 'Dick', 'Larry' ],
  241.     };
  242.  
  243. template:
  244.  
  245.     [% people.0 %]            # Tom
  246.     [% people.1 %]            # Dick
  247.     [% people.2 %]            # Larry
  248.  
  249. The FOREACH directive can be used to iterate through items in a list.
  250.  
  251.     [% FOREACH person = people %]
  252.     Hello [% person %]
  253.     [% END %]
  254.  
  255. output:
  256.  
  257.     Hello Tom
  258.     Hello Dick
  259.     Hello Larry
  260.  
  261. Lists can be constructed in-situ using the regular anonymous list
  262. '[' ... ']' construct.  Commas between items are optional.
  263.  
  264.     [% cols = [ 'red', 'green', 'blue' ] %]
  265.  
  266.     [% FOREACH c = cols %]
  267.        ...
  268.  
  269. or:
  270.  
  271.     [% FOREACH c = [ 'red', 'green', 'blue' ] %]
  272.        ...
  273.  
  274. You can also create simple numerical sequences using the familiar '..'
  275. operator:
  276.  
  277.     [% n = [ 1 .. 4 ] %]    # n is [ 1, 2, 3, 4 ] 
  278.  
  279.     [% x = 4
  280.        y = 8
  281.        z = [x..y]           # z is [ 4, 5, 6, 7, 8 ]
  282.     %]
  283.  
  284. =head2 Subroutines
  285.  
  286. Template variables can contain references to Perl subroutines.  When
  287. the variable is used, the Template Toolkit will automatically call the
  288. subroutine, passing any additional arguments specified.  The return
  289. value from the subroutine is used as the variable value and inserted
  290. into the document output.
  291.  
  292.     my $vars = {
  293.     wizard  => sub { return join(' ', 'Abracadabra!', @_) },
  294.     };    
  295.  
  296. template:
  297.  
  298.     [% wizard %]            # Abracadabra!
  299.     [% wizard('Hocus Pocus!') %]    # Abracadabra! Hocus Pocus!
  300.  
  301.  
  302. =head2 Objects
  303.  
  304. Template variables can also contain references to Perl objects.
  305. Methods are called using the dot operator to specify the method
  306. against the object variable.  Additional arguments can be specified
  307. as with subroutines.
  308.  
  309.     use CGI;
  310.  
  311.     ...
  312.  
  313.     my $vars = {
  314.     # hard coded CGI params for purpose of example
  315.     cgi  => CGI->new('mode=submit&debug=1'),
  316.     };
  317.  
  318. template:
  319.  
  320.     [% FOREACH p = cgi.param %]        # returns list of param keys
  321.     [% p %] => [% cgi.param(p) %]    # fetch each param value
  322.     [% END %]
  323.  
  324. output:
  325.  
  326.     mode => submit
  327.     debug => 1
  328.  
  329. Object methods can also be called as lvalues.  That is, they can appear on 
  330. the left side of an assignment.  The method will be called passing the 
  331. assigning value as an argument.  
  332.  
  333.     [% myobj.method = 10 %]
  334.  
  335. equivalent to:
  336.  
  337.     [% myobj.method(10) %]
  338.  
  339. =head2 Parameters and Return Values
  340.  
  341. Subroutines and methods will be passed any arguments specified in the
  342. template.  Any template variables in the argument list will first be
  343. evaluated and their resultant values passed to the code.
  344.  
  345.     my $vars = {
  346.     mycode => sub { return 'received ' . join(', ', @_) },
  347.     };
  348.  
  349. template:
  350.  
  351.     [% foo = 10 %]
  352.     [% mycode(foo, 20) %]        # received 10, 20
  353.  
  354. Named parameters may also be specified.  These are automatically collected
  355. into a single hash array which is passed by reference as the B<last> 
  356. parameter to the sub-routine.  Named parameters can be specified using
  357. either '=E<gt>' or '=' and can appear anywhere in the argument list.
  358.  
  359.     my $vars = {
  360.     myjoin => \&myjoin,
  361.     };
  362.  
  363.     sub myjoin {
  364.     # look for hash ref as last argument
  365.     my $params = ref $_[-1] eq 'HASH' ? pop : { };
  366.     return join($params->{ joint } || ' + ', @_);
  367.     }
  368.  
  369. template:
  370.  
  371.     [% myjoin(10, 20, 30) %]
  372.     [% myjoin(10, 20, 30, joint = ' - ' %]
  373.     [% myjoin(joint => ' * ', 10, 20, 30 %]
  374.  
  375. output:
  376.  
  377.     10 + 20 + 30
  378.     10 - 20 - 30
  379.     10 * 20 * 30
  380.  
  381. Parenthesised parameters may be added to any element of a variable,
  382. not just those that are bound to code or object methods.  At present,
  383. parameters will be ignored if the variable isn't "callable" but are 
  384. supported for future extensions.  Think of them as "hints" to that 
  385. variable, rather than just arguments passed to a function.
  386.  
  387.     [% r = 'Romeo' %]
  388.     [% r(100, 99, s, t, v) %]        # outputs "Romeo"
  389.  
  390. User code should return a value for the variable it represents. This
  391. can be any of the Perl data types described above: a scalar, or
  392. reference to a list, hash, subroutine or object.  Where code returns a
  393. list of multiple values the items will automatically be folded into a
  394. list reference which can be accessed as per normal.
  395.  
  396.     my $vars = {
  397.     # either is OK, first is recommended
  398.     items1 => sub { return [ 'foo', 'bar', 'baz' ] },
  399.     items2 => sub { return ( 'foo', 'bar', 'baz' ) },
  400.     };
  401.  
  402. template:
  403.  
  404.     [% FOREACH i = items1 %]
  405.        ...
  406.     [% END %]
  407.  
  408.     [% FOREACH i = items2 %]
  409.        ...
  410.     [% END %]
  411.  
  412. =head2 Error Handling
  413.  
  414. Errors can be reported from user code by calling die().  Errors raised
  415. in this way are caught by the Template Toolkit and converted to
  416. structured exceptions which can be handled from within the template.
  417. A reference to the exception object is then available as the 'error'
  418. variable.
  419.  
  420.     my $vars = {
  421.     barf => sub { 
  422.         die "a sick error has occurred\n";
  423.     },
  424.     };
  425.  
  426. template:
  427.  
  428.     [% TRY %]
  429.        [% barf %]        # calls sub which throws error via die()
  430.     [% CATCH %]
  431.        [% error.info %]        # outputs "a sick error has occurred\n"
  432.     [% END %]
  433.  
  434. Error messages thrown via die() are converted to exceptions of type
  435. 'undef'.  Exceptions of user-defined types can be thrown by calling
  436. die() with a reference to a Template::Exception object.
  437.  
  438.     use Template::Exception;
  439.  
  440.     ...
  441.     
  442.     my $vars = {
  443.     login => sub { 
  444.         ...
  445.         die Template::Exception->new('badpwd',
  446.                      'password too silly');
  447.     },
  448.     };
  449.  
  450. template:
  451.  
  452.     [% TRY %]
  453.        [% login %]
  454.     [% CATCH badpwd %]
  455.        Bad password: [% error.info %]
  456.     [% CATCH %]
  457.        Some other '[% error.type %]' error: [% error.info %]
  458.     [% END %]
  459.  
  460. The exception types 'stop' and 'return' are used to implement the 
  461. STOP and RETURN directives.  Throwing an exception as:
  462.  
  463.     die (Template::Exception->new('stop'));
  464.  
  465. has the same effect as the directive:
  466.  
  467.     [% STOP %]
  468.  
  469. Subroutines and methods can also raise errors by returning a list or
  470. reference to a list containing the undefined value (undef) followed by
  471. an exception object or error message.  This is supported for backwards
  472. compatibility with version 1 but may be deprecated in some future
  473. version.
  474.  
  475.     my $vars = {
  476.     # currently equivalent
  477.     barf => sub {
  478.         die "I'm sorry Dave, I can't do that";
  479.     },
  480.     yack => sub {
  481.         return (undef, "I'm sorry Dave, I can't do that");
  482.     },
  483.     };
  484.  
  485. =head2 Virtual Methods
  486.  
  487. The Template Toolkit implements a number of "virtual methods" which 
  488. can be applied to scalars, hashes or lists.  For example:
  489.  
  490.     [% mylist = [ 'foo', 'bar', 'baz' ] %]
  491.     [% newlist = mylist.sort %]
  492.  
  493. Here 'mylist' is a regular reference to a list, and 'sort' is 
  494. a virtual method that returns a new list of the items in sorted 
  495. order.  You can chain multiple virtual methods together.  For
  496. example:
  497.  
  498.     [% mylist.sort.join(', ') %]
  499.  
  500. Here the 'join' virtual method is called to join the sorted list into
  501. a single string, generating the following output:
  502.  
  503.     bar, baz, foo
  504.  
  505. See L<Template::Manual::VMethods> for details of all the virtual 
  506. methods available.
  507.  
  508. =head2 Variable Interpolation
  509.  
  510. The Template Toolkit uses '$' consistently to indicate that a variable
  511. should be interpolated in position.  Most frequently, you see this in 
  512. double-quoted strings:
  513.  
  514.     [% fullname = "$honorific $firstname $surname" %]
  515.  
  516. Or embedded in plain text when the INTERPOLATE option is set:
  517.  
  518.     Dear $honorific $firstname $surname,
  519.  
  520. The same rules apply within directives.  If a variable is prefixed
  521. with a '$' then it is replaced with its value before being used.  The
  522. most common use is to retrieve an element from a hash where the key is
  523. stored in a variable.
  524.  
  525.     [% uid = 'abw' %]
  526.     [% userlist.$uid %]            # same as 'userlist.abw'
  527.  
  528. Curly braces can be used to delimit interpolated variable names where
  529. necessary.
  530.  
  531.     [% userlist.${me.id}.name %]    
  532.  
  533. Directives such as INCLUDE, PROCESS, etc., that accept a template name
  534. as the first argument, will automatically quote it for convenience.
  535.  
  536.     [% INCLUDE foo/bar.txt %]
  537.  
  538. equivalent to:
  539.  
  540.     [% INCLUDE "foo/bar.txt" %]
  541.  
  542. To INCLUDE a template whose name is stored in a variable, simply
  543. prefix the variable name with '$' to have it interpolated.
  544.  
  545.     [% myfile = 'header' %]
  546.     [% INCLUDE $myfile %]
  547.  
  548. equivalent to:
  549.  
  550.     [% INCLUDE header %]
  551.  
  552. Note also that a variable containing a reference to a Template::Document
  553. object can also be processed in this way.
  554.  
  555.     my $vars = {
  556.     header => Template::Document->new({ ... }),
  557.     };
  558.  
  559. template:
  560.  
  561.     [% INCLUDE $header %]
  562.  
  563. =head2 Local and Global Variables
  564.  
  565. Any simple variables that you create, or any changes you make to
  566. existing variables, will only persist while the template is being
  567. processed.  The top-level variable hash is copied before processing
  568. begins and any changes to variables are made in this copy, leaving the
  569. original intact.  The same thing happens when you INCLUDE another
  570. template.  The current namespace hash is cloned to prevent any
  571. variable changes made in the included template from interfering with
  572. existing variables.  The PROCESS option bypasses the localisation step
  573. altogether making it slightly faster, but requiring greater attention
  574. to the possibility of side effects caused by creating or changing any
  575. variables within the processed template.
  576.  
  577.     [% BLOCK change_name %]
  578.        [% name = 'bar' %]
  579.     [% END %]
  580.  
  581.     [% name = 'foo' %] 
  582.     [% INCLUDE change_name %]
  583.     [% name %]                # foo
  584.     [% PROCESS change_name %]
  585.     [% name %]                # bar
  586.  
  587. Dotted compound variables behave slightly differently because the
  588. localisation process is only skin deep.  The current variable
  589. namespace hash is copied, but no attempt is made to perform a
  590. deep-copy of other structures within it (hashes, arrays, objects,
  591. etc).  A variable referencing a hash, for example, will be copied to
  592. create a new reference but which points to the same hash.  Thus, the
  593. general rule is that simple variables (undotted variables) are
  594. localised, but existing complex structures (dotted variables) are not.
  595.  
  596.     [% BLOCK all_change %]
  597.        [% x = 20 %]            # changes copy
  598.        [% y.z = 'zulu' %]        # changes original
  599.     [% END %]
  600.  
  601.     [% x = 10
  602.        y = { z => 'zebra' }
  603.     %]
  604.     [% INCLUDE all_change %]
  605.     [% x %]                # still '10'
  606.     [% y.z %]                # now 'zulu'
  607.  
  608.  
  609. If you create a complex structure such as a hash or list reference
  610. within a local template context then it will cease to exist when 
  611. the template is finished processing.  
  612.  
  613.     [% BLOCK new_stuff %]
  614.        [% # define a new 'y' hash array in local context
  615.           y = { z => 'zulu' }
  616.        %]
  617.     [% END %]
  618.  
  619.     [% x = 10 %]
  620.     [% INCLUDE new_stuff %]
  621.     [% x %]                # outputs '10'
  622.     [% y %]                # nothing, y is undefined
  623.  
  624. Similarly, if you update an element of a compound variable which
  625. I<doesn't> already exists then a hash will be created automatically
  626. and deleted again at the end of the block.
  627.  
  628.     [% BLOCK new_stuff %]
  629.        [% y.z = 'zulu' %]
  630.     [% END %]
  631.  
  632. However, if the hash I<does> already exist then you will modify the
  633. original with permanent effect.  To avoid potential confusion, it is
  634. recommended that you don't update elements of complex variables from
  635. within blocks or templates included by another.
  636.  
  637. If you want to create or update truly global variables then you can 
  638. use the 'global' namespace.  This is a hash array automatically created
  639. in the top-level namespace which all templates, localised or otherwise
  640. see the same reference to.  Changes made to variables within this
  641. hash are visible across all templates.
  642.  
  643.     [% global.version = 123 %]
  644.  
  645. =head2 Compile Time Constant Folding
  646.  
  647. In addition to variables that get resolved each time a template is
  648. processed, you can also define variables that get resolved just once
  649. when the template is compiled.  This generally results in templates
  650. processing faster because there is less work to be done.
  651.  
  652. To define compile-time constants, specify a CONSTANTS hash as a
  653. constructor item as per VARIABLES.  The CONSTANTS hash can contain any
  654. kind of complex, nested, or dynamic data structures, just like regular
  655. variables.
  656.  
  657.     my $tt = Template->new({
  658.     CONSTANTS => {
  659.         version => 3.14,
  660.         release => 'skyrocket',
  661.         col     => {
  662.         back => '#ffffff',
  663.         fore => '#000000',
  664.         },
  665.         myobj => My::Object->new(),
  666.         mysub => sub { ... },
  667.         joint => ', ',
  668.     },
  669.     });
  670.  
  671. Within a template, you access these variables using the 'constants'
  672. namespace prefix.
  673.  
  674.     Version [% constants.version %] ([% constants.release %])
  675.  
  676.     Background: [% constants.col.back %]
  677.  
  678. When the template is compiled, these variable references are replaced
  679. with the corresponding value.  No further variable lookup is then 
  680. required when the template is processed.
  681.  
  682. You can call subroutines, object methods, and even virtual methods on
  683. constant variables.
  684.  
  685.     [% constants.mysub(10, 20) %]
  686.     [% constants.myobj(30, 40) %]
  687.     [% constants.col.keys.sort.join(', ') %]
  688.  
  689. One important proviso is that any arguments you pass to subroutines
  690. or methods must also be literal values or compile time constants.
  691.  
  692. For example, these are both fine:
  693.  
  694.     # literal argument
  695.     [% constants.col.keys.sort.join(', ') %]
  696.  
  697.     # constant argument
  698.     [% constants.col.keys.sort.join(constants.joint) %]
  699.  
  700. But this next example will raise an error at parse time because
  701. 'joint' is a runtime variable and cannot be determined at compile
  702. time.
  703.  
  704.     # ERROR: runtime variable argument!
  705.     [% constants.col.keys.sort.join(joint) %]
  706.  
  707. The CONSTANTS_NAMESPACE option can be used to provide a different 
  708. namespace prefix for constant variables.  For example:
  709.  
  710.     my $tt = Template->new({
  711.     CONSTANTS => {
  712.         version => 3.14,
  713.         # ...etc...
  714.     },
  715.     CONSTANTS_NAMESPACE => 'const',
  716.     });
  717.  
  718. Constants would then be referenced in templates as:
  719.  
  720.     [% const.version %]
  721.  
  722. =head2 Special Variables
  723.  
  724. A number of special variables are automatically defined by the Template 
  725. Toolkit.
  726.  
  727. =over 4
  728.  
  729. =item template
  730.  
  731. The 'template' variable contains a reference to the main template
  732. being processed, in the form of a Template::Document object.  This
  733. variable is correctly defined within PRE_PROCESS, PROCESS and
  734. POST_PROCESS templates, allowing standard headers, footers, etc., to
  735. access metadata items from the main template.  The 'name' and
  736. 'modtime' metadata items are automatically provided, giving the
  737. template name and modification time in seconds since the epoch.  
  738.  
  739. Note that the 'template' variable always references the top-level
  740. template, even when processing other template components via INCLUDE,
  741. PROCESS, etc.
  742.  
  743. =item component
  744.  
  745. The 'component' variable is like 'template' but always contains a
  746. reference to the current, innermost template component being processed.
  747. In the main template, the 'template' and 'component' variable will 
  748. reference the same Template::Document object.  In any other template
  749. component called from the main template, the 'template' variable 
  750. will remain unchanged, but 'component' will contain a new reference
  751. to the current component.
  752.  
  753. This example should demonstrate the difference:
  754.  
  755.     $template->process('foo')
  756.     || die $template->error(), "\n";
  757.  
  758. 'foo':
  759.  
  760.     [% template.name %]            # foo
  761.     [% component.name %]        # foo
  762.     [% PROCESS footer %]
  763.  
  764. 'footer':
  765.  
  766.     [% template.name %]            # foo
  767.     [% component.name %]            # footer
  768.  
  769. =item loop
  770.  
  771. Within a FOREACH loop, the 'loop' variable references the Template::Iterator
  772. object responsible for controlling the loop.
  773.  
  774.     [% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]
  775.        [% "Items:\n" IF loop.first -%]
  776.        [% loop.count %]/[% loop.size %]: [% item %]
  777.     [% END %]
  778.  
  779. =item error
  780.  
  781. Within a CATCH block, the 'error' variable contains a reference to the 
  782. Template::Exception object thrown from within the TRY block.  The 
  783. 'type' and 'info' methods can be called or the variable itself can 
  784. be printed for automatic stringification into a message of the form
  785. "$type error - $info".  See L<Template::Exception> for further details.
  786.  
  787.     [% TRY %]
  788.        ...
  789.     [% CATCH %]
  790.        [% error %]
  791.     [% END %]
  792.  
  793. =item content
  794.  
  795. The WRAPPER method captures the output from a template block and then 
  796. includes a named template, passing the captured output as the 'content'
  797. variable.
  798.  
  799.     [% WRAPPER box %]
  800.     Be not afeard; the isle is full of noises,
  801.     Sounds and sweet airs, that give delight and hurt not.
  802.     [% END %]
  803.  
  804.     [% BLOCK box %]
  805.     <table border=1>
  806.     <tr>
  807.       <td>
  808.       [% content %]
  809.       </td>
  810.     </tr>
  811.     </table>
  812.     [% END %]
  813.  
  814. =back
  815.  
  816. =head2 Compound Variables
  817.  
  818. Compound 'dotted' variables may contain any number of separate
  819. elements.  Each element may evaluate to any of the permitted variable
  820. types and the processor will then correctly use this value to evaluate
  821. the rest of the variable.  Arguments may be passed to any of the
  822. intermediate elements.
  823.  
  824.     [% myorg.people.sort('surname').first.fullname %]
  825.  
  826. Intermediate variables may be used and will behave entirely as expected.
  827.  
  828.     [% sorted = myorg.people.sort('surname') %]
  829.     [% sorted.first.fullname %]
  830.  
  831. This simplified dotted notation has the benefit of hiding the
  832. implementation details of your data.  For example, you could implement
  833. a data structure as a hash array one day and then change it to an
  834. object the next without requiring any change to the templates.
  835.  
  836. =head1 AUTHOR
  837.  
  838. Andy Wardley E<lt>abw@andywardley.comE<gt>
  839.  
  840. L<http://www.andywardley.com/|http://www.andywardley.com/>
  841.  
  842.  
  843.  
  844.  
  845. =head1 VERSION
  846.  
  847. Template Toolkit version 2.13, released on 30 January 2004.
  848.  
  849. =head1 COPYRIGHT
  850.  
  851.   Copyright (C) 1996-2004 Andy Wardley.  All Rights Reserved.
  852.   Copyright (C) 1998-2002 Canon Research Centre Europe Ltd.
  853.  
  854. This module is free software; you can redistribute it and/or
  855. modify it under the same terms as Perl itself.
  856.  
  857.  
  858.  
  859. =cut
  860.  
  861. # Local Variables:
  862. # mode: perl
  863. # perl-indent-level: 4
  864. # indent-tabs-mode: nil
  865. # End:
  866. #
  867. # vim: expandtab shiftwidth=4:
  868.