Your IP : 13.59.135.139


Current Path : /usr/share/doc/perl-Template-Toolkit-2.24/old/manual/
Upload File :
Current File : //usr/share/doc/perl-Template-Toolkit-2.24/old/manual/Variables.html


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
  <head>
    <title>Template::Manual::Variables</title>
    <link rel="stylesheet" type="text/css" href="../css/blue.css" title="Clear Blue">
    <link rel="alternate stylesheet" type="text/css" href="../css/orange.css" title="Clear Orange">
    <link rel="alternate stylesheet" type="text/css" href="../css/green.css" title="Clear Green">
    <link rel="alternate stylesheet" type="text/css" href="../css/purple.css" title="Clear Purple">
    <link rel="alternate stylesheet" type="text/css" href="../css/grey.css" title="Clear Grey">
    <!--[if IE 6]>
    <link rel="stylesheet" type="text/css" href="../css/ie6.css" />
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/print.css" media="print">
    <script type="text/javascript" src="../js/tt2.js"></script>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <meta name="author" content="Andy Wardley">
  </head>
  <body id="body"> 
    <div id="layout">
        <div id="header">
          <a href="../index.html" id="logo" alt="" title="Click for the Home Page"><span class="alt">TT2 Home Page</span></a>
          <ul id="trail">
            <li><a href="../manual/index.html">Manual</a></li>
            <li class="last"><a href="../manual/Variables.html">Variables</a></li>
          </ul>
          <div class="controls">
            <a href="#" class="menu show" onclick="widescreen_off(); return false" title="Show Menu">
              <span class="about">Click to view the menu.  It's very nice.</span>
            </a>
            <a href="#" class="menu hide" onclick="widescreen_on();  return false" title="Hide Menu">
              <span class="about">Click to hide the menu and go all widescreen!</span>
            </a>
          
          <div class="pager">
            <a href="../manual/Directives.html" title="Template::Manual::Directives" class="go back">Back<span class="about"><h4>Template::Manual::Directives</h4>Template directives</span></a>
            <a href="../manual/index.html" title="Template::Manual" class="go up">Up<span class="about"><h4>Template::Manual</h4>Template Toolkit User Manual</span></a>
            <a href="../manual/VMethods.html" title="Template::Manual::VMethods" class="go next">Next<span class="about"><h4>Template::Manual::VMethods</h4>Virtual Methods</span></a>
          </div>
          </div>
          <h1 class="headline">Template::Manual::Variables</h1>
          <h2 class="subhead">Template variables and code bindings</h1>
        
        </div>
        <div id="page">
          <div id="sidebar">
            <a href="../index.html" id="logo"></a>
            <div id="menu">
              <ul class="menu">
                <li class="l0 first"><a href="../manual/index.html" class="warm">Manual</a></li>
                <li class="l1"><a href="../manual/Intro.html">Intro</a></li>
                <li class="l1"><a href="../manual/Syntax.html">Syntax</a></li>
                <li class="l1"><a href="../manual/Directives.html">Directives</a></li>
                <li class="l1"><a href="../manual/Variables.html" class="warm">Variables</a></li>
                <li class="l1"><a href="../manual/VMethods.html">VMethods</a></li>
                <li class="l1"><a href="../manual/Config.html">Config</a></li>
                <li class="l1"><a href="../manual/Filters.html">Filters</a></li>
                <li class="l1"><a href="../manual/Plugins.html">Plugins</a></li>
                <li class="l1"><a href="../manual/Internals.html">Internals</a></li>
                <li class="l1"><a href="../manual/Views.html">Views</a></li>
                <li class="l1"><a href="../manual/Credits.html">Credits</a></li>
                <li class="l0"><a href="../modules/index.html">Modules</a></li>
                <li class="l0"><a href="../tools/index.html">Tools</a></li>
                <li class="l0 last"><a href="../tutorial/index.html">Tutorial</a></li>
              </ul>
              <div class="foot"></div>
            </div>
          </div>
          <div id="content">
          <div class="section">
            <div class="head">
              <h1 id="contents" onclick="switch_section(this)" title="Click title to show/hide section content.">Contents</h1>
              <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
            </div>
            <div class="body">
              <ul class="toc">
                  <li class=""><a href="#Template_Variables">Template Variables</a></li>
                  <li class="sub"><a href="#section_Scalar_Values">Scalar Values</a></li>
                  <li class="sub"><a href="#section_Hash_Array_References">Hash Array References</a></li>
                  <li class="sub"><a href="#section_List_References">List References</a></li>
                  <li class="sub"><a href="#section_Subroutines">Subroutines</a></li>
                  <li class="sub"><a href="#section_Objects">Objects</a></li>
                  <li class="sub"><a href="#section_Passing_Parameters_and_Returning_Values">Passing Parameters and Returning Values</a></li>
                  <li class="sub"><a href="#section_Error_Handling">Error Handling</a></li>
                  <li class=""><a href="#Virtual_Methods">Virtual Methods</a></li>
                  <li class=""><a href="#Variable_Interpolation">Variable Interpolation</a></li>
                  <li class=""><a href="#Local_and_Global_Variables">Local and Global Variables</a></li>
                  <li class=""><a href="#Compile_Time_Constant_Folding">Compile Time Constant Folding</a></li>
                  <li class=""><a href="#Special_Variables">Special Variables</a></li>
                  <li class="sub"><a href="#section_template">template</a></li>
                  <li class="sub"><a href="#section_component">component</a></li>
                  <li class="sub"><a href="#section_loop">loop</a></li>
                  <li class="sub"><a href="#section_error">error</a></li>
                  <li class="sub"><a href="#section_content">content</a></li>
                  <li class=""><a href="#Compound_Variables">Compound Variables</a></li>
              
              </ul>
            </div>
          </div>
          
                <div class="pod">
            <div class="section">
              <div class="head">
                <h1 id="Template_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Template Variables</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      A reference to a hash array may be passed as the second argument to the
                      <a href="#method_process">Template#process()</a> method, containing
                      definitions of template variables. The <code>VARIABLES</code> (a.k.a.
                      <code>PRE_DEFINE</code>) option can also be used to pre-define variables
                      for all templates processed by the object.
                    </p>
                    <pre>my $tt = Template-&gt;new({
    VARIABLES =&gt; {
        version =&gt; 3.14,
        release =&gt; 'Sahara',
    },  
});

my $vars = {
    serial_no =&gt; 271828,
};

$tt-&gt;process('myfile', $vars);</pre>
                    <p>
                      <i>myfile</i> template:
                    </p>
                    <pre>This is version [% version %] ([% release %]).
Serial number: [% serial_no %]</pre>
                    <p>
                      Generated Output:
                    </p>
                    <pre>This is version 3.14 (Sahara)
Serial number: 271828</pre>
                    <p>
                      Variable names may contain any alphanumeric characters or underscores.
                      They may be lower, upper or mixed case although the usual convention is
                      to use lower case. The case <i>is</i> significant however, and
                      '<code>foo</code>', '<code>Foo</code>' and '<code>FOO</code>' are all
                      different variables. Upper case variable names are permitted, but not
                      recommended due to a possible conflict with an existing or future
                      reserved word. As of version 2.00, these are:
                    </p>
                    <pre>GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER 
IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP 
CLEAR TO STEP AND OR NOT MOD DIV END</pre>
                    <p>
                      The variable values may be of virtually any Perl type, including simple
                      scalars, references to lists, hash arrays, subroutines or objects. The
                      Template Toolkit will automatically apply the correct procedure to
                      accessing these values as they are used in the template.
                    </p>
                    <p>
                      Example data:
                    </p>
                    <pre>my $vars = {
    article =&gt; 'The Third Shoe',
    person  =&gt; { 
        id    =&gt; 314, 
        name  =&gt; 'Mr. Blue',
        email =&gt; 'blue@nowhere.org',
    },
    primes  =&gt; [ 2, 3, 5, 7, 11, 13 ],
    wizard  =&gt; sub { return join(' ', 'Abracadabra!', @_) },
    cgi     =&gt; CGI-&gt;new('mode=submit&amp;debug=1'),
};</pre>
                    <p>
                      Example template:
                    </p>
                    <pre>[% article %]

[% person.id %]: [% person.name %] &lt;[% person.email %]&gt;

[% primes.first %] - [% primes.last %], including [% primes.3 %]
[% primes.size %] prime numbers: [% primes.join(', ') %]

[% wizard %]
[% wizard('Hocus Pocus!') %]

[% cgi.param('mode') %]</pre>
                    <p>
                      Generated output:
                    </p>
                    <pre>The Third Shoe

314: Mr. Blue &lt;blue@nowhere.org&gt;

2 - 13, including 7
6 prime numbers: 2, 3, 5, 7, 11, 13

Abracadabra!
Abracadabra! Hocus Pocus!

submit</pre>
                    <div class="subsection">
                  <div class="head">
                    <h2 id="section_Scalar_Values" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Scalar Values</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Regular scalar variables are accessed by simply specifying their name. As
                          these are just entries in the top-level variable hash they can be
                          considered special cases of hash array referencing as described below,
                          with the main namespace hash automatically implied.
                        </p>
                        <pre>[% article %]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_Hash_Array_References" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Hash Array References</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Members of hash arrays are accessed by specifying the hash reference and
                          key separated by the dot '<code>.</code>' operator.
                        </p>
                        <p>
                          Example data:
                        </p>
                        <pre>my $vars = {
    'home' =&gt; 'http://www.myserver.com/homepage.html',
    'page' =&gt; {
        'this' =&gt; 'mypage.html',
        'next' =&gt; 'nextpage.html',
        'prev' =&gt; 'prevpage.html',
    },
};</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>&lt;a href="[% home %]"&gt;Home&lt;/a&gt;
&lt;a href="[% page.prev %]"&gt;Previous Page&lt;/a&gt;
&lt;a href="[% page.next %]"&gt;Next Page&lt;/a&gt;</pre>
                        <p>
                          Generated output:
                        </p>
                        <pre>&lt;a href="http://www.myserver.com/homepage.html"&gt;Home&lt;/a&gt;
&lt;a href="prevpage.html"&gt;Previous Page&lt;/a&gt;
&lt;a href="nextpage.html"&gt;Next Page&lt;/a&gt;</pre>
                        <p>
                          Any key in a hash which starts with a '<code>_</code>' or
                          '<code>.</code>' character will be considered private and cannot be
                          evaluated or updated from within a template. The undefined value will be
                          returned for any such variable accessed which the Template Toolkit will
                          silently ignore (unless the <code>DEBUG</code> option is enabled).
                        </p>
                        <p>
                          Example data:
                        </p>
                        <pre>my $vars = {
    message =&gt; 'Hello World!',
    _secret =&gt; "On the Internet, no-one knows you're a dog",
    thing   =&gt; {
        public    =&gt; 123,
        _private  =&gt; 456,
        '.hidden' =&gt; 789,
    },
};</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% message %]           # outputs "Hello World!"
[% _secret %]           # no output
[% thing.public %]      # outputs "123"
[% thing._private %]    # no output
[% thing..hidden %]     # ERROR: unexpected token (..)</pre>
                        <p>
                          You can disable this feature by setting the
                          <code>$Template::Stash::PRIVATE</code> package variable to a false value.
                        </p>
                        <pre>$Template::Stash::PRIVATE = undef;   # now you can thing._private</pre>
                        <p>
                          To access a hash entry using a key stored in another variable, prefix the
                          key variable with '<code>$</code>' to have it interpolated before use
                          (see <a href="#Variable_Interpolation">Variable Interpolation</a>).
                        </p>
                        <pre>[% pagename = 'next' %]
[% page.$pagename %]       # same as [% page.next %]</pre>
                        <p>
                          When you assign to a variable that contains multiple namespace elements
                          (i.e. it has one or more '<code>.</code>' characters in the name), any
                          hashes required to represent intermediate namespaces will be created
                          automatically. In this following example, the <code>product</code>
                          variable automatically springs into life as a hash array unless otherwise
                          defined.
                        </p>
                        <pre>[% product.id    = 'XYZ-2000' 
   product.desc  = 'Bogon Generator'
   product.price = 666 
%]

The [% product.id %] [% product.desc %] 
costs $[% product.price %].00</pre>
                        <p>
                          Generated output:
                        </p>
                        <pre>The XYZ-2000 Bogon Generator 
costs $666.00</pre>
                        <p>
                          You can use Perl's familiar <code>{</code> ... <code>}</code> construct
                          to explicitly create a hash and assign it to a variable. Note that commas
                          are optional between key/value pairs and <code>=</code> can be used in
                          place of <code>=&gt;</code>.
                        </p>
                        <pre># minimal TT style
[% product = {
     id    = 'XYZ-2000'
     desc  = 'Bogon Generator'
     price = 666
   }
%]</pre>
                        <pre># perl style
[% product = {
     id    =&gt; 'XYZ-2000',
     desc  =&gt; 'Bogon Generator',
     price =&gt; 666,
   }
%]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_List_References" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">List References</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Items in lists are also accessed by use of the dot operator.
                        </p>
                        <p>
                          Example data:
                        </p>
                        <pre>my $vars = {
    people =&gt; [ 'Tom', 'Dick', 'Larry' ],
};</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% people.0 %]          # Tom
[% people.1 %]          # Dick
[% people.2 %]          # Larry</pre>
                        <p>
                          The <code>FOREACH</code> directive can be used to iterate through items
                          in a list.
                        </p>
                        <pre>[% FOREACH person IN people %]
Hello [% person %]
[% END %]</pre>
                        <p>
                          Generated output:
                        </p>
                        <pre>Hello Tom
Hello Dick
Hello Larry</pre>
                        <p>
                          Lists can be constructed in-situ using the regular anonymous list
                          <code>[</code> ... <code>]</code> construct. Commas between items are
                          optional.
                        </p>
                        <pre>[% cols = [ 'red', 'green', 'blue' ] %]

[% FOREACH c IN cols %]
   [% c %]
[% END %]</pre>
                        <p>
                          or:
                        </p>
                        <pre>[% FOREACH c IN [ 'red', 'green', 'blue' ] %]
   [% c %]
[% END %]</pre>
                        <p>
                          You can also create simple numerical sequences using the <code>..</code>
                          range operator:
                        </p>
                        <pre>[% n = [ 1 .. 4 ] %]    # n is [ 1, 2, 3, 4 ] 

[% x = 4
   y = 8
   z = [x..y]           # z is [ 4, 5, 6, 7, 8 ]
%]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_Subroutines" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Subroutines</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Template variables can contain references to Perl subroutines. When the
                          variable is used, the Template Toolkit will automatically call the
                          subroutine, passing any additional arguments specified. The return value
                          from the subroutine is used as the variable value and inserted into the
                          document output.
                        </p>
                        <pre>my $vars = {
    wizard  =&gt; sub { return join(' ', 'Abracadabra!', @_) },
};  </pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% wizard %]                    # Abracadabra!
[% wizard('Hocus Pocus!') %]    # Abracadabra! Hocus Pocus!</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_Objects" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Objects</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Template variables can also contain references to Perl objects. Methods
                          are called using the dot operator to specify the method against the
                          object variable. Additional arguments can be specified as with
                          subroutines.
                        </p>
                        <pre>use CGI;

my $vars = {
    # hard coded CGI params for purpose of example
    cgi  =&gt; CGI-&gt;new('mode=submit&amp;debug=1'),
};</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% FOREACH p IN cgi.param %]     # returns list of param keys
[% p %] =&gt; [% cgi.param(p) %]   # fetch each param value
[% END %]</pre>
                        <p>
                          Generated output:
                        </p>
                        <pre>mode =&gt; submit
debug =&gt; 1</pre>
                        <p>
                          Object methods can also be called as lvalues. That is, they can appear on
                          the left side of an assignment. The method will be called passing the
                          assigning value as an argument.
                        </p>
                        <pre>[% myobj.method = 10 %]</pre>
                        <p>
                          equivalent to:
                        </p>
                        <pre>[% myobj.method(10) %]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_Passing_Parameters_and_Returning_Values" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Passing Parameters and Returning Values</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Subroutines and methods will be passed any arguments specified in the
                          template. Any template variables in the argument list will first be
                          evaluated and their resultant values passed to the code.
                        </p>
                        <pre>my $vars = {
    mycode =&gt; sub { return 'received ' . join(', ', @_) },
};</pre>
                        <p>
                          template:
                        </p>
                        <pre>[% foo = 10 %]
[% mycode(foo, 20) %]       # received 10, 20</pre>
                        <p>
                          Named parameters may also be specified. These are automatically collected
                          into a single hash array which is passed by reference as the <b>last</b>
                          parameter to the sub-routine. Named parameters can be specified using
                          either <code>=&gt;</code> or <code>=</code> and can appear anywhere in
                          the argument list.
                        </p>
                        <pre>my $vars = {
    myjoin =&gt; \&amp;myjoin,
};

sub myjoin {
    # look for hash ref as last argument
    my $params = ref $_[-1] eq 'HASH' ? pop : { };
    return join($params-&gt;{ joint } || ' + ', @_);
}</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% myjoin(10, 20, 30) %]
[% myjoin(10, 20, 30, joint = ' - ' %]
[% myjoin(joint =&gt; ' * ', 10, 20, 30 %]</pre>
                        <p>
                          Generated output:
                        </p>
                        <pre>10 + 20 + 30
10 - 20 - 30
10 * 20 * 30</pre>
                        <p>
                          Parenthesised parameters may be added to any element of a variable, not
                          just those that are bound to code or object methods. At present,
                          parameters will be ignored if the variable isn't "callable" but are
                          supported for future extensions. Think of them as "hints" to that
                          variable, rather than just arguments passed to a function.
                        </p>
                        <pre>[% r = 'Romeo' %]
[% r(100, 99, s, t, v) %]       # outputs "Romeo"</pre>
                        <p>
                          User code should return a value for the variable it represents. This can
                          be any of the Perl data types described above: a scalar, or reference to
                          a list, hash, subroutine or object. Where code returns a list of multiple
                          values the items will automatically be folded into a list reference which
                          can be accessed as per normal.
                        </p>
                        <pre>my $vars = {
    # either is OK, first is recommended
    items1 =&gt; sub { return [ 'foo', 'bar', 'baz' ] },
    items2 =&gt; sub { return ( 'foo', 'bar', 'baz' ) },
};</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% FOREACH i IN items1 %]
   ...
[% END %]

[% FOREACH i IN items2 %]
   ...
[% END %]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_Error_Handling" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Error Handling</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Errors can be reported from user code by calling <code>die()</code>.
                          Errors raised in this way are caught by the Template Toolkit and
                          converted to structured exceptions which can be handled from within the
                          template. A reference to the exception object is then available as the
                          <code>error</code> variable.
                        </p>
                        <pre>my $vars = {
    barf =&gt; sub { 
        die "a sick error has occurred\n";
    },
};</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% TRY %]
   [% barf %]       # calls sub which throws error via die()
[% CATCH %]
   [% error.info %]     # outputs "a sick error has occurred\n"
[% END %]</pre>
                        <p>
                          Error messages thrown via <code>die()</code> are converted to exceptions
                          of type <code>undef</code> (the literal string "undef" rather than the
                          undefined value). Exceptions of user-defined types can be thrown by
                          calling <code>die()</code> with a reference to a <a href="../modules/Template/Exception.html">Template::Exception</a> object.
                        </p>
                        <pre>use Template::Exception;

my $vars = {
    login =&gt; sub { 
        ...do something...
        die Template::Exception-&gt;new( badpwd =&gt; 'password too silly' );
    },
};</pre>
                        <p>
                          Example template:
                        </p>
                        <pre>[% TRY %]
   [% login %]
[% CATCH badpwd %]
   Bad password: [% error.info %]
[% CATCH %]
   Some other '[% error.type %]' error: [% error.info %]
[% END %]</pre>
                        <p>
                          The exception types <code>stop</code> and <code>return</code> are used to
                          implement the <code>STOP</code> and <code>RETURN</code> directives.
                          Throwing an exception as:
                        </p>
                        <pre>die (Template::Exception-&gt;new('stop'));</pre>
                        <p>
                          has the same effect as the directive:
                        </p>
                        <pre>[% STOP %]</pre>
                  </div>
                </div>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Virtual_Methods" onclick="switch_section(this)" title="Click title to show/hide section content.">Virtual Methods</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      The Template Toolkit implements a number of "virtual methods" which can
                      be applied to scalars, hashes or lists. For example:
                    </p>
                    <pre>[% mylist = [ 'foo', 'bar', 'baz' ] %]
[% newlist = mylist.sort %]</pre>
                    <p>
                      Here <code>mylist</code> is a regular reference to a list, and 'sort' is
                      a virtual method that returns a new list of the items in sorted order.
                      You can chain multiple virtual methods together. For example:
                    </p>
                    <pre>[% mylist.sort.join(', ') %]</pre>
                    <p>
                      Here the <code>join</code> virtual method is called to join the sorted
                      list into a single string, generating the following output:
                    </p>
                    <pre>bar, baz, foo</pre>
                    <p>
                      See <a href="../manual/VMethods.html">Template::Manual::VMethods</a> for details of all the virtual
                      methods available.
                    </p>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Variable_Interpolation" onclick="switch_section(this)" title="Click title to show/hide section content.">Variable Interpolation</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      The Template Toolkit uses <code>$</code> consistently to indicate that a
                      variable should be interpolated in position. Most frequently, you see
                      this in double-quoted strings:
                    </p>
                    <pre>[% fullname = "$honorific $firstname $surname" %]</pre>
                    <p>
                      Or embedded in plain text when the <code>INTERPOLATE</code> option is
                      set:
                    </p>
                    <pre>Dear $honorific $firstname $surname,</pre>
                    <p>
                      The same rules apply within directives. If a variable is prefixed with a
                      <code>$</code> then it is replaced with its value before being used. The
                      most common use is to retrieve an element from a hash where the key is
                      stored in a variable.
                    </p>
                    <pre>[% uid = 'abw' %]
[% users.$uid %]         # same as 'userlist.abw'</pre>
                    <p>
                      Curly braces can be used to delimit interpolated variable names where
                      necessary.
                    </p>
                    <pre>[% users.${me.id}.name %]    </pre>
                    <p>
                      Directives such as <code>INCLUDE</code>, <code>PROCESS</code>, etc., that
                      accept a template name as the first argument, will automatically quote it
                      for convenience.
                    </p>
                    <pre>[% INCLUDE foo/bar.txt %]</pre>
                    <p>
                      The above example is equivalent to:
                    </p>
                    <pre>[% INCLUDE "foo/bar.txt" %]</pre>
                    <p>
                      To <code>INCLUDE</code> a template whose name is stored in a variable,
                      simply prefix the variable name with <code>$</code> to have it
                      interpolated.
                    </p>
                    <pre>[% myfile = 'header' %]
[% INCLUDE $myfile %]</pre>
                    <p>
                      This is equivalent to:
                    </p>
                    <pre>[% INCLUDE header %]</pre>
                    <p>
                      Note also that a variable containing a reference to a <a href="../modules/Template/Document.html">Template::Document</a> object can
                      also be processed in this way.
                    </p>
                    <pre>my $vars = {
    header =&gt; Template::Document-&gt;new({ ... }),
};</pre>
                    <p>
                      Example template:
                    </p>
                    <pre>[% INCLUDE $header %]</pre>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Local_and_Global_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Local and Global Variables</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      Any simple variables that you create, or any changes you make to existing
                      variables, will only persist while the template is being processed. The
                      top-level variable hash is copied before processing begins and any
                      changes to variables are made in this copy, leaving the original intact.
                    </p>
                    <p>
                      The same thing happens when you <code>INCLUDE</code> another template.
                      The current namespace hash is cloned to prevent any variable changes made
                      in the included template from interfering with existing variables. The
                      <code>PROCESS</code> option bypasses the localisation step altogether
                      making it slightly faster, but requiring greater attention to the
                      possibility of side effects caused by creating or changing any variables
                      within the processed template.
                    </p>
                    <pre>[% BLOCK change_name %]
   [% name = 'bar' %]
[% END %]

[% name = 'foo' %] 
[% INCLUDE change_name %]
[% name %]              # foo
[% PROCESS change_name %]
[% name %]              # bar</pre>
                    <p>
                      Dotted compound variables behave slightly differently because the
                      localisation process is only skin deep. The current variable namespace
                      hash is copied, but no attempt is made to perform a deep-copy of other
                      structures within it (hashes, arrays, objects, etc). A variable
                      referencing a hash, for example, will be copied to create a new reference
                      but which points to the same hash. Thus, the general rule is that simple
                      variables (undotted variables) are localised, but existing complex
                      structures (dotted variables) are not.
                    </p>
                    <pre>[% BLOCK all_change %]
   [% x = 20 %]         # changes copy
   [% y.z = 'zulu' %]       # changes original
[% END %]

[% x = 10
   y = { z =&gt; 'zebra' }
%]
[% INCLUDE all_change %]
[% x %]             # still '10'
[% y.z %]               # now 'zulu'</pre>
                    <p>
                      If you create a complex structure such as a hash or list reference within
                      a local template context then it will cease to exist when the template is
                      finished processing.
                    </p>
                    <pre>[% BLOCK new_stuff %]
   [% # define a new 'y' hash array in local context
      y = { z =&gt; 'zulu' }
   %]
[% END %]

[% x = 10 %]
[% INCLUDE new_stuff %]
[% x %]             # outputs '10'
[% y %]             # nothing, y is undefined</pre>
                    <p>
                      Similarly, if you update an element of a compound variable which
                      <i>doesn't</i> already exists then a hash will be created automatically
                      and deleted again at the end of the block.
                    </p>
                    <pre>[% BLOCK new_stuff %]
   [% y.z = 'zulu' %]
[% END %]</pre>
                    <p>
                      However, if the hash <i>does</i> already exist then you will modify the
                      original with permanent effect. To avoid potential confusion, it is
                      recommended that you don't update elements of complex variables from
                      within blocks or templates included by another.
                    </p>
                    <p>
                      If you want to create or update truly global variables then you can use
                      the 'global' namespace. This is a hash array automatically created in the
                      top-level namespace which all templates, localised or otherwise see the
                      same reference to. Changes made to variables within this hash are visible
                      across all templates.
                    </p>
                    <pre>[% global.version = 123 %]</pre>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Compile_Time_Constant_Folding" onclick="switch_section(this)" title="Click title to show/hide section content.">Compile Time Constant Folding</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      In addition to variables that get resolved each time a template is
                      processed, you can also define variables that get resolved just once when
                      the template is compiled. This generally results in templates processing
                      faster because there is less work to be done.
                    </p>
                    <p>
                      To define compile-time constants, specify a <code>CONSTANTS</code> hash
                      as a constructor item as per <code>VARIABLES</code>. The
                      <code>CONSTANTS</code> hash can contain any kind of complex, nested, or
                      dynamic data structures, just like regular variables.
                    </p>
                    <pre>my $tt = Template-&gt;new({
    CONSTANTS =&gt; {
        version =&gt; 3.14,
        release =&gt; 'skyrocket',
        col     =&gt; {
            back =&gt; '#ffffff',
            fore =&gt; '#000000',
        },
        myobj =&gt; My::Object-&gt;new(),
        mysub =&gt; sub { ... },
        joint =&gt; ', ',
    },
});</pre>
                    <p>
                      Within a template, you access these variables using the
                      <code>constants</code> namespace prefix.
                    </p>
                    <pre>Version [% constants.version %] ([% constants.release %])
Background: [% constants.col.back %]</pre>
                    <p>
                      When the template is compiled, these variable references are replaced
                      with the corresponding value. No further variable lookup is then required
                      when the template is processed.
                    </p>
                    <p>
                      You can call subroutines, object methods, and even virtual methods on
                      constant variables.
                    </p>
                    <pre>[% constants.mysub(10, 20) %]
[% constants.myobj(30, 40) %]
[% constants.col.keys.sort.join(', ') %]</pre>
                    <p>
                      One important proviso is that any arguments you pass to subroutines or
                      methods must also be literal values or compile time constants.
                    </p>
                    <p>
                      For example, these are both fine:
                    </p>
                    <pre># literal argument
[% constants.col.keys.sort.join(', ') %]

# constant argument
[% constants.col.keys.sort.join(constants.joint) %]</pre>
                    <p>
                      But this next example will raise an error at parse time because
                      <code>joint</code> is a runtime variable and cannot be determined at
                      compile time.
                    </p>
                    <pre># ERROR: runtime variable argument!
[% constants.col.keys.sort.join(joint) %]</pre>
                    <p>
                      The <code>CONSTANTS_NAMESPACE</code> option can be used to provide a
                      different namespace prefix for constant variables. For example:
                    </p>
                    <pre>my $tt = Template-&gt;new({
    CONSTANTS =&gt; {
        version =&gt; 3.14,
        # ...etc...
    },
    CONSTANTS_NAMESPACE =&gt; 'const',
});</pre>
                    <p>
                      Constants would then be referenced in templates as:
                    </p>
                    <pre>[% const.version %]</pre>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Special_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Special Variables</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      A number of special variables are automatically defined by the Template
                      Toolkit.
                    </p>
                    <div class="subsection">
                  <div class="head">
                    <h2 id="section_template" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">template</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          The <code>template</code> variable contains a reference to the main
                          template being processed, in the form of a <a href="../modules/Template/Document.html">Template::Document</a> object. This
                          variable is correctly defined within <code>PRE_PROCESS</code>,
                          <code>PROCESS</code> and <code>POST_PROCESS</code> templates, allowing
                          standard headers, footers, etc., to access metadata items from the main
                          template. The <code>name</code> and <code>modtime</code> metadata items
                          are automatically provided, giving the template name and modification
                          time in seconds since the epoch.
                        </p>
                        <p>
                          Note that the <code>template</code> variable always references the
                          top-level template, even when processing other template components via
                          <code>INCLUDE</code>, <code>PROCESS</code>, etc.
                        </p>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_component" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">component</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          The <code>component</code> variable is like <code>template</code> but
                          always contains a reference to the current, innermost template component
                          being processed. In the main template, the <code>template</code> and
                          <code>component</code> variable will reference the same <a href="../modules/Template/Document.html">Template::Document</a> object. In
                          any other template component called from the main template, the
                          <code>template</code> variable will remain unchanged, but
                          <code>component</code> will contain a new reference to the current
                          component.
                        </p>
                        <p>
                          This example should demonstrate the difference:
                        </p>
                        <pre>$template-&gt;process('foo')
    || die $template-&gt;error(), "\n";</pre>
                        <p>
                          <i>foo</i> template:
                        </p>
                        <pre>[% template.name %]         # foo
[% component.name %]        # foo
[% PROCESS footer %]</pre>
                        <p>
                          <i>footer</i> template:
                        </p>
                        <pre>[% template.name %]         # foo
[% component.name %]        # footer</pre>
                        <p>
                          Additionally, the <code>component</code> variable has two special fields:
                          <code>caller</code> and <code>callers</code>. <code>caller</code>
                          contains the name of the template that called the current template (or
                          undef if the values of <code>template</code> and <code>component</code>
                          are the same). <code>callers</code> contains a reference to a list of all
                          the templates that have been called on the road to calling the current
                          component template (like a call stack), with the outer-most template
                          first.
                        </p>
                        <p>
                          Here's an example:
                        </p>
                        <p>
                          <i>outer.tt2</i> template:
                        </p>
                        <pre>[% component.name %]        # 'outer.tt2'
[% component.caller %]      # undef
[% component.callers %]     # undef
[% PROCESS 'middle.tt2' %]</pre>
                        <p>
                          <i>middle.tt2</i> template:
                        </p>
                        <pre>[% component.name %]        # 'middle.tt2'
[% component.caller %]      # 'outer.tt2'
[% component.callers %]     # [ 'outer.tt2' ]
[% PROCESS 'inner.tt2' %]</pre>
                        <p>
                          <i>inner.tt2</i> template:
                        </p>
                        <pre>[% component.name %]        # 'inner.tt2'
[% component.caller %]      # 'middle.tt2'
[% component.callers %]     # [ 'outer.tt2', 'middle.tt2' ]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_loop" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">loop</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Within a <code>FOREACH</code> loop, the <code>loop</code> variable
                          references the <a href="../modules/Template/Iterator.html">Template::Iterator</a> object responsible for controlling the loop.
                        </p>
                        <pre>[% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]
   [% "Items:\n" IF loop.first -%]
   [% loop.count %]/[% loop.size %]: [% item %]
[% END %]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_error" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">error</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Within a <code>CATCH</code> block, the <code>error</code> variable
                          contains a reference to the <a href="../modules/Template/Exception.html">Template::Exception</a> object thrown from within the
                          <code>TRY</code> block. The <code>type</code> and <code>info</code>
                          methods can be called or the variable itself can be printed for automatic
                          stringification into a message of the form "<code>$type error -
                          $info</code>". See <a href="../modules/Template/Exception.html">Template::Exception</a> for further details.
                        </p>
                        <pre>[% TRY %]
   ...
[% CATCH %]
   [% error %]
[% END %]</pre>
                  </div>
                </div>    <div class="subsection">
                  <div class="head">
                    <h2 id="section_content" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">content</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          The <code>WRAPPER</code> method captures the output from a template block
                          and then includes a named template, passing the captured output as the
                          'content' variable.
                        </p>
                        <pre>[% WRAPPER box %]
Be not afeard; the isle is full of noises,
Sounds and sweet airs, that give delight and hurt not.
[% END %]</pre>
                        <pre>[% BLOCK box %]
&lt;blockquote class="prose"&gt;
  [% content %]
&lt;/blockquote&gt;
[% END %]</pre>
                  </div>
                </div>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Compound_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Compound Variables</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      Compound 'dotted' variables may contain any number of separate elements.
                      Each element may evaluate to any of the permitted variable types and the
                      processor will then correctly use this value to evaluate the rest of the
                      variable. Arguments may be passed to any of the intermediate elements.
                    </p>
                    <pre>[% myorg.people.sort('surname').first.fullname %]</pre>
                    <p>
                      Intermediate variables may be used and will behave entirely as expected.
                    </p>
                    <pre>[% sorted = myorg.people.sort('surname') %]
[% sorted.first.fullname %]</pre>
                    <p>
                      This simplified dotted notation has the benefit of hiding the
                      implementation details of your data. For example, you could implement a
                      data structure as a hash array one day and then change it to an object
                      the next without requiring any change to the templates.
                    </p>
              </div>
            </div>
            
            </div></div>
          <br class="clear" />
          <div class="pageinfo">
            /manual/Variables.html last modified 10:57:42 31-May-2007
          </div>
        </div>
        
        <div id="footer">
          <a href="http://opensource.org/" class="osi"></a>
          <div class="controls">
          <div class="pager">
            <a href="../manual/Directives.html" title="Template::Manual::Directives" class="go back">Back<span class="about"><h4>Template::Manual::Directives</h4></span></a>
            <a href="../manual/index.html" title="Template::Manual" class="go up">Up<span class="about"><h4>Template::Manual</h4></span></a>
            <a href="../manual/VMethods.html" title="Template::Manual::VMethods" class="go next">Next<span class="about"><h4>Template::Manual::VMethods</h4></span></a>
          </div>
          </div>
          <div class="copyright">
            Copyright &copy; 1996-2007 <a href="http://wardley.org/">Andy Wardley</a>.  All Rights Reserved.
          </div>
          <div class="licence">
            The <a href="http://template-toolkit.org/">Template Toolkit</a> is <a href="http://opensource.org/">Open Source</a> software.
            You can redistribute and/or modify it under the terms of the <a href="http://www.opensource.org/licenses/gpl-license.php">GNU Public Licence</a>
            or the <a href="http://www.opensource.org/licenses/artistic-license.php">Perl Artistic Licence</a>.
          </div>
        </div>
        <div id="palette">
          <ul>
            <li class="first"><a href="#" class="blue" onclick="set_style('Clear Blue')"></a></li>
            <li><a href="#" class="orange" onclick="set_style('Clear Orange')"></a></li>
            <li><a href="#" class="green" onclick="set_style('Clear Green')"></a></li>
            <li><a href="#" class="purple" onclick="set_style('Clear Purple')"></a></li>
            <li><a href="#" class="grey" onclick="set_style('Clear Grey')"></a></li>
          </ul>
        </div>
    </div>  </body>
</html>