[%# # IMPORTANT NOTE # This documentation is generated automatically from source # templates. Any changes you make here may be lost. # # The 'docsrc' documentation source bundle is available for download # from http://www.template-toolkit.org/docs.html and contains all # the source templates, XML files, scripts, etc., from which the # documentation for the Template Toolkit is built. -%] [% META book = 'Manual' page = 'Variables' %] [% WRAPPER toc; PROCESS tocitem title ='DESCRIPTION' subs = [ 'Template Variables', 'Scalar Values', 'Hash Array References', 'List References', 'Subroutines', 'Objects', 'Parameters and Return Values', 'Error Handling', 'Virtual Variable Methods', 'Compound Variables', 'Variable Interpolation', 'Local and Global Variables', 'Special Variables' ]; PROCESS tocitem title ='AUTHOR' subs = []; PROCESS tocitem title ='VERSION' subs = []; PROCESS tocitem title ='COPYRIGHT' subs = []; END %] [% WRAPPER section title='DESCRIPTION' -%]

This section describes the different ways in which Perl data can be bound to template variables and accessed via Template Toolkit directives.

[% WRAPPER subsection title = 'Template Variables' -%]

A reference to a hash array may be passed as the second argument to the process() method, containing definitions of template variables. The VARIABLES (a.k.a. PRE_DEFINE) option can also be used to pre-define variables for all templates processed by the object.

        my $tt = Template->new({
    	VARIABLES => {
    	    version => 3.14,
    	    release => 'Sahara',
    	},
        });

        my $vars = {
    	serial_no => 271828,
        };

        $tt->process('myfile', $vars);

'myfile':

        This is version [% tt_start_tag %] version [% tt_end_tag %] ([% tt_start_tag %] release [% tt_end_tag %]).
        Serial number: [% tt_start_tag %] serial_no [% tt_end_tag %]

output:

        This is version 3.14 (Sahara)
        Serial number: 271828

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 is significant however, and 'foo', 'Foo' and 'FOO' 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:

            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

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.

Example:

        my $vars = {
    	article => 'The Third Shoe',
    	person  => {
    	    id    => 314,
    	    name  => 'Mr. Blue',
    	    email => 'blue@nowhere.org',
    	},
    	primes  => [ 2, 3, 5, 7, 11, 13 ],
    	wizard  => sub { return join(' ', 'Abracadabra!', @_) },
    	cgi     => CGI->new('mode=submit&debug=1'),
        };

template:

        [% tt_start_tag %] article [% tt_end_tag %]

        [% tt_start_tag %] person.id [% tt_end_tag %]: [% tt_start_tag %] person.name [% tt_end_tag %] <[% tt_start_tag %] person.email [% tt_end_tag %]>

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

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

        [% tt_start_tag %] cgi.param('mode') [% tt_end_tag %]

output:

        The Third Shoe

        314: Mr. Blue <blue@nowhere.org>

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

        Abracadabra!
        Abracadabra! Hocus Pocus!

        submit

[%- END %] [% WRAPPER subsection title = 'Scalar Values' -%]

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.

        [% tt_start_tag %] article [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = 'Hash Array References' -%]

Members of hash arrays are accessed by specifying the hash reference and key separated by the dot '.' operator.

        my $vars = {
      	'home' => 'http://www.myserver.com/homepage.html',
      	'page' => {
      	    'this' => 'mypage.html',
      	    'next' => 'nextpage.html',
      	    'prev' => 'prevpage.html',
      	},
        };

template:

        <a href="[% tt_start_tag %] home [% tt_end_tag %]">Home</a>
        <a href="[% tt_start_tag %] page.prev [% tt_end_tag %]">Previous Page</a>
        <a href="[% tt_start_tag %] page.next [% tt_end_tag %]">Next Page</a>

output:

        <a href="http://www.myserver.com/homepage.html">Home</a>
        <a href="prevpage.html">Previous Page</a>
        <a href="nextpage.html">Next Page</a>

Any key in a hash which starts with a '_' or '.' 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 DEBUG option is enabled).

        my $vars = {
    	message => 'Hello World!',
    	_secret => "On the Internet, no-one knows you're a dog",
    	thing   => {
    	     public  => 123,
    	    _private => 456,
    	   '.hidden' => 789,
    	},
        };

template:

        [% tt_start_tag %] message [% tt_end_tag %]		# outputs "Hello World!"
        [% tt_start_tag %] _secret [% tt_end_tag %]               # no output
        [% tt_start_tag %] thing.public [% tt_end_tag %]          # outputs "123"
        [% tt_start_tag %] thing._private [% tt_end_tag %]        # no output
        [% tt_start_tag %] thing..hidden [% tt_end_tag %]         # ERROR: unexpected token (..)

To access a hash entry using a key stored in another variable, prefix the key variable with '$' to have it interpolated before use (see [% ttlink('Variable Interpolation') -%]).

        [% tt_start_tag %] pagename = 'next' [% tt_end_tag %]
        [% tt_start_tag %] page.$pagename [% tt_end_tag %]       # same as [% tt_start_tag %] page.next [% tt_end_tag %]

When you assign to a variable that contains multiple namespace elements (i.e. it has one or more '.' characters in the name), any hashes required to represent intermediate namespaces will be created automatically. In this following example, the 'product' variable automatically springs into life as a hash array unless otherwise defined.

        [% tt_start_tag %] product.id    = 'XYZ-2000'
           product.desc  = 'Bogon Generator'
           product.price = 666
        [% tt_end_tag %]

        The [% tt_start_tag %] product.id [% tt_end_tag %] [% tt_start_tag %] product.desc [% tt_end_tag %]
        costs $[% tt_start_tag %] product.price [% tt_end_tag %].00

output:

        The XYZ-2000 Bogon Generator
        costs $666.00

You can use Perl's familiar '{' ... '}' construct to explicitly create a hash and assign it to a variable. Note that commas are optional between key/value pairs and '=' can be used in place of '=>'.

        [% tt_start_tag %] product = {
      	 id    => 'XYZ-2000',
      	 desc  => 'Bogon Generator',
      	 price => 666,
           }
        [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = 'List References' -%]

Items in lists are also accessed by use of the dot operator.

        my $vars = {
      	'people' => [ 'Tom', 'Dick', 'Larry' ],
        };

template:

        [% tt_start_tag %] people.0 [% tt_end_tag %]			# Tom
        [% tt_start_tag %] people.1 [% tt_end_tag %]			# Dick
        [% tt_start_tag %] people.2 [% tt_end_tag %]			# Larry

The FOREACH directive can be used to iterate through items in a list.

        [% tt_start_tag %] FOREACH person = people [% tt_end_tag %]
        Hello [% tt_start_tag %] person [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

output:

        Hello Tom
        Hello Dick
        Hello Larry

Lists can be constructed in-situ using the regular anonymous list '[' ... ']' construct. Commas between items are optional.

        [% tt_start_tag %] cols = [ 'red', 'green', 'blue' ] [% tt_end_tag %]

        [% tt_start_tag %] FOREACH c = cols [% tt_end_tag %]
           ...

or:

        [% tt_start_tag %] FOREACH c = [ 'red', 'green', 'blue' ] [% tt_end_tag %]
           ...

You can also create simple numerical sequences using the familiar '..' operator:

        [% tt_start_tag %] n = [ 1 .. 4 ] [% tt_end_tag %]    # n is [ 1, 2, 3, 4 ]

        [% tt_start_tag %] x = 4
           y = 8
           z = [x..y]           # z is [ 4, 5, 6, 7, 8 ]
        [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = 'Subroutines' -%]

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.

        my $vars = {
    	wizard  => sub { return join(' ', 'Abracadabra!', @_) },
        };

template:

        [% tt_start_tag %] wizard [% tt_end_tag %]			# Abracadabra!
        [% tt_start_tag %] wizard('Hocus Pocus!') [% tt_end_tag %]	# Abracadabra! Hocus Pocus!

[%- END %] [% WRAPPER subsection title = 'Objects' -%]

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.

        use CGI;

        ...

        my $vars = {
    	# hard coded CGI params for purpose of example
    	cgi  => CGI->new('mode=submit&debug=1'),
        };

template:

        [% tt_start_tag %] FOREACH p = cgi.param [% tt_end_tag %]		# returns list of param keys
        [% tt_start_tag %] p [% tt_end_tag %] => [% tt_start_tag %] cgi.param(p) [% tt_end_tag %]	# fetch each param value
        [% tt_start_tag %] END [% tt_end_tag %]

output:

        mode => submit
        debug => 1

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.

        [% tt_start_tag %] myobj.method = 10 [% tt_end_tag %]

equivalent to:

        [% tt_start_tag %] myobj.method(10) [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = 'Parameters and Return Values' -%]

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.

        my $vars = {
    	mycode => sub { return 'received ' . join(', ', @_) },
        };

template:

        [% tt_start_tag %] foo = 10 [% tt_end_tag %]
        [% tt_start_tag %] mycode(foo, 20) [% tt_end_tag %]		# received 10, 20

Named parameters may also be specified. These are automatically collected into a single hash array which is passed by reference as the last parameter to the sub-routine. Named parameters can be specified using either '=>' or '=' and can appear anywhere in the argument list.

        my $vars = {
    	myjoin => \&myjoin,
        };

        sub myjoin {
    	# look for hash ref as last argument
    	my $params = ref $_[-1] eq 'HASH' ? pop : { };
    	return join($params->{ joint } || ' + ', @_);
        }

template:

        [% tt_start_tag %] myjoin(10, 20, 30) [% tt_end_tag %]
        [% tt_start_tag %] myjoin(10, 20, 30, joint = ' - ' [% tt_end_tag %]
        [% tt_start_tag %] myjoin(joint => ' * ', 10, 20, 30 [% tt_end_tag %]

output:

        10 + 20 + 30
        10 - 20 - 30
        10 * 20 * 30

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.

        [% tt_start_tag %] r = 'Romeo' [% tt_end_tag %]
        [% tt_start_tag %] r(100, 99, s, t, v) [% tt_end_tag %]		# outputs "Romeo"

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.

        my $vars = {
    	# either is OK, first is recommended
    	items1 => sub { return [ 'foo', 'bar', 'baz' ] },
    	items2 => sub { return ( 'foo', 'bar', 'baz' ) },
        };

template:

        [% tt_start_tag %] FOREACH i = items1 [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] FOREACH i = items2 [% tt_end_tag %]
           ...
        [% tt_start_tag %] END [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = 'Error Handling' -%]

Errors can be reported from user code by calling die(). 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 'error' variable.

        my $vars = {
    	barf => sub {
    	    die "a sick error has occurred\n";
    	},
        };

template:

        [% tt_start_tag %] TRY [% tt_end_tag %]
           [% tt_start_tag %] barf [% tt_end_tag %]	    # calls sub which throws error via die()
        [% tt_start_tag %] CATCH [% tt_end_tag %]
           [% tt_start_tag %] error.info [% tt_end_tag %]	    # outputs "a sick error has occurred\n"
        [% tt_start_tag %] END [% tt_end_tag %]

Error messages thrown via die() are converted to exceptions of type 'undef'. Exceptions of user-defined types can be thrown by calling die() with a reference to a Template::Exception object.

        use Template::Exception;

        ...

        my $vars = {
    	login => sub {
    	    ...
    	    die Template::Exception->new('badpwd',
    					 'password too silly');
    	},
        };

template:

        [% tt_start_tag %] TRY [% tt_end_tag %]
           [% tt_start_tag %] login [% tt_end_tag %]
        [% tt_start_tag %] CATCH badpwd [% tt_end_tag %]
           Bad password: [% tt_start_tag %] error.info [% tt_end_tag %]
        [% tt_start_tag %] CATCH [% tt_end_tag %]
           Some other '[% tt_start_tag %] error.type [% tt_end_tag %]' error: [% tt_start_tag %] error.info [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

The exception types 'stop' and 'return' are used to implement the STOP and RETURN directives. Throwing an exception as:

        die Template::Exception->new('stop');

has the same effect as the directive:

        [% tt_start_tag %] STOP [% tt_end_tag %]

Subroutines and methods can also raise errors by returning a list or reference to a list containing the undefined value (undef) followed by an exception object or error message. This is supported for backwards compatibility with version 1 but may be deprecated in some future version.

        my $vars = {
    	# currently equivalent
    	barf => sub {
    	    die "I'm sorry Dave, I can't do that";
    	},
    	yack => sub {
    	    return (undef, "I'm sorry Dave, I can't do that");
    	},
        };

[%- END %] [% WRAPPER subsection title = 'Virtual Variable Methods' -%]

The Template Toolkit provides virtual methods for manipulating variable values. Most of them are analogous to regular Perl functions of the same names.

The following methods can be called against any scalar value:

- defined

  Returns true if the value is defined.

          [% tt_start_tag %] user = get_user(uid) IF uid.defined [% tt_end_tag %]

- length

  Returns the length of the string representation of the item:

          [% tt_start_tag %] IF password.length < 8 [% tt_end_tag %]
             Password too short, dumbass!
          [% tt_start_tag %] END [% tt_end_tag %]

- repeat(n)

  Repeat the string a specified number of times.

          [% tt_start_tag %] name = 'foo' [% tt_end_tag %]
          [% tt_start_tag %] name.repeat(3) [% tt_end_tag %]		# foofoofoo

- replace(search, replace)

  Outputs the string with all instances of the first argument (specified as a Perl regular expression) with the second.

          [% tt_start_tag %] name = 'foo, bar & baz' [% tt_end_tag %]
          [% tt_start_tag %] name.replace('\W+', '_') [% tt_end_tag %]    # foo_bar_baz

- search(pattern)

  Returns true if the string matches the regular expression pattern passed as an argument.

          [% tt_start_tag %] name = 'foo bar baz' [% tt_end_tag %]
          [% tt_start_tag %] name.search('bar') ? 'bar' : 'no bar' [% tt_end_tag %]	    # bar

- split(pattern)

  Calls Perl's split() function to split a string into a list of strings.

          [% tt_start_tag %] FOREACH dir = mypath.split(':') [% tt_end_tag %]
             [% tt_start_tag %] dir [% tt_end_tag %]
          [% tt_start_tag %] END [% tt_end_tag %]

The following can be called against hash references.

- keys, values, each

  The regular hash operators returning lists of keys, values or both. Note how we use a '$' prefix on the 'key' variable in this example to have it interpolated (i.e. replaced with its value) before use.

          [% tt_start_tag %] FOREACH key = product.keys [% tt_end_tag %]
             [% tt_start_tag %] key [% tt_end_tag %] => [% tt_start_tag %] product.$key [% tt_end_tag %]
          [% tt_start_tag %] END [% tt_end_tag %]

- sort, nsort

  Return a list of the keys, sorted alphabetically (sort) or numerically (nsort) according to the corresponding values in the hash.

          [% tt_start_tag %] FOREACH n = phones.sort [% tt_end_tag %]
             [% tt_start_tag %] phones.$n [% tt_end_tag %] is [% tt_start_tag %] n [% tt_end_tag %],
          [% tt_start_tag %] END [% tt_end_tag %]

- import

  The import method can be called on a hash array to import the contents of another hash array.

          [% tt_start_tag %] hash1 = {
      	   foo => 'Foo',
                 bar => 'Bar',
             }
             hash2 = {
                 wiz => 'Wiz',
                 woz => 'Woz',
             }
          [% tt_end_tag %]

          [% tt_start_tag %] hash1.import(hash2) [% tt_end_tag %]
          [% tt_start_tag %] hash1.wiz [% tt_end_tag %]			# Wiz

  You can also call the import() method by itself to import a hash array into the current namespace hash.

          [% tt_start_tag %] user = { id => 'lwall', name => 'Larry Wall' } [% tt_end_tag %]
          [% tt_start_tag %] import(user) [% tt_end_tag %]
          [% tt_start_tag %] id [% tt_end_tag %]: [% tt_start_tag %] name [% tt_end_tag %]		# lwall: Larry Wall

The following virtual methods are provided for lists:

- first, last

  Returns the first/last item in the list. The item is not removed from the list.

          [% tt_start_tag %] results.first [% tt_end_tag %] to [% tt_start_tag %] results.last [% tt_end_tag %]

- size, max

  Returns the size of a list (number of elements) and the maximum index number (size - 1), respectively.

          [% tt_start_tag %] results.size [% tt_end_tag %] search results matched your query

- reverse

  Returns the items of the list in reverse order.

          [% tt_start_tag %] FOREACH s = scores.reverse [% tt_end_tag %]
             ...
          [% tt_start_tag %] END [% tt_end_tag %]

- join

  Joins the items in the list into a single string, using Perl's join function.

          [% tt_start_tag %] items.join(', ') [% tt_end_tag %]

- sort, nsort

  Returns the items in alpha (sort) or numerical (nsort) order.

          [% tt_start_tag %] library = books.sort [% tt_end_tag %]

  Where the list contains hash array references, a hash key can be passed as an argument to specify the sort field.

          [% tt_start_tag %] library = books.sort('author') [% tt_end_tag %]

- unshift(item), push(item)

  Adds an item to the start/end of a list.

          [% tt_start_tag %] mylist.unshift('prev item') [% tt_end_tag %]
          [% tt_start_tag %] mylist.push('next item')    [% tt_end_tag %]

- shift, pop

  Removes the first/last item from the list and returns it.

          [% tt_start_tag %] first = mylist.shift [% tt_end_tag %]
          [% tt_start_tag %] last  = mylist.pop   [% tt_end_tag %]

The following example demonstrates how an empty list ('folk') can be populated with formatted strings by using the push() method in conjunction with a FOREACH loop. The resultant list can then be printed using join.

        [% tt_start_tag %] # define some initial data
           people   => [
               { id => 'tom',   name => 'Tom'     },
    	   { id => 'dick',  name => 'Richard' },
               { id => 'larry', name => 'Larry'   },
           ]

           # define an empty list that list methods can be called against
           folk = []
        -[% tt_end_tag %]

        [% tt_start_tag %] folk.push("<a href=\"${person.id}.html\">$person.name</a>")
             FOREACH person = people.sort('name') -[% tt_end_tag %]
        [% tt_start_tag %] folk.join(",\n") [% tt_end_tag %]

Output:

        <a href="larry.html">Larry</a>,
        <a href="dick.html">Richard</a>,
        <a href="tom.html">Tom</a>

You can define your own virtual methods for scalars, lists and hash arrays. The Template::Stash package variables $SCALAR_OPS, $LIST_OPS and $HASH_OPS are references to hash arrays that define these virtual methods. HASH_OPS and LIST_OPS methods are subroutines that accept a hash/list reference as the first item. SCALAR_OPS are subroutines that accept a scalar value as the first item. Any other arguments specified when the method is called will be passed to the subroutine.

        # load Template::Stash to make method tables visible
        use Template::Stash;

        # define list method to return new list of odd numbers only
        $Template::Stash::LIST_OPS->{ odd } = sub {
    	my $list = shift;
    	return [ grep { $_ % 2 } @$list ];
        };

template:

        [% tt_start_tag %] primes = [ 2, 3, 5, 7, 9 ] [% tt_end_tag %]
        [% tt_start_tag %] primes.odd.join(', ') [% tt_end_tag %]		# 3, 5, 7, 9

See also the examples in the t/vmeth.t test script.

[%- END %] [% WRAPPER subsection title = 'Compound Variables' -%]

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.

        [% tt_start_tag %] myorg.people.sort('surname').first.fullname [% tt_end_tag %]

Intermediate variables may be used and will behave entirely as expected.

        [% tt_start_tag %] sorted = myorg.people.sort('surname') [% tt_end_tag %]
        [% tt_start_tag %] sorted.first.fullname [% tt_end_tag %]

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.

[%- END %] [% WRAPPER subsection title = 'Variable Interpolation' -%]

The Template Toolkit uses '$' consistently to indicate that a variable should be interpolated in position. Most frequently, you see this in double-quoted strings:

        [% tt_start_tag %] fullname = "$honorific $firstname $surname" [% tt_end_tag %]

Or embedded in plain text when the INTERPOLATE option is set:

        Dear $honorific $firstname $surname,

The same rules apply within directives. If a variable is prefixed with a '$' 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.

        [% tt_start_tag %] uid = 'abw' [% tt_end_tag %]
        [% tt_start_tag %] userlist.$uid [% tt_end_tag %]		    # same as 'userlist.abw'

Curly braces can be used to delimit interpolated variable names where necessary.

        [% tt_start_tag %] userlist.${me.id}.name [% tt_end_tag %]

Directives such as INCLUDE, PROCESS, etc., that accept a template name as the first argument, will automatically quote it for convenience.

        [% tt_start_tag %] INCLUDE foo/bar.txt [% tt_end_tag %]

equivalent to:

        [% tt_start_tag %] INCLUDE "foo/bar.txt" [% tt_end_tag %]

To INCLUDE a template whose name is stored in a variable, simply prefix the variable name with '$' to have it interpolated.

        [% tt_start_tag %] myfile = 'header' [% tt_end_tag %]
        [% tt_start_tag %] INCLUDE $myfile [% tt_end_tag %]

equivalent to:

        [% tt_start_tag %] INCLUDE header [% tt_end_tag %]

Note also that a variable containing a reference to a Template::Document object can also be processed in this way.

        my $vars = {
    	header => Template::Document->new({ ... }),
        };

template:

        [% tt_start_tag %] INCLUDE $header [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = 'Local and Global Variables' -%]

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. The same thing happens when you INCLUDE another template. The current namespace hash is cloned to prevent any variable changes made in the included template from interfering with existing variables. The PROCESS 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.

        [% tt_start_tag %] BLOCK change_name [% tt_end_tag %]
           [% tt_start_tag %] name = 'bar' [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] name = 'foo' [% tt_end_tag %]
        [% tt_start_tag %] INCLUDE change_name [% tt_end_tag %]
        [% tt_start_tag %] name [% tt_end_tag %]			    # foo
        [% tt_start_tag %] PROCESS change_name [% tt_end_tag %]
        [% tt_start_tag %] name [% tt_end_tag %]			    # bar

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.

        [% tt_start_tag %] BLOCK all_change [% tt_end_tag %]
           [% tt_start_tag %] x = 20 [% tt_end_tag %]		    # changes copy
           [% tt_start_tag %] y.z = 'zulu' [% tt_end_tag %]	    # changes original
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] x = 10
           y = { z => 'zebra' }
        [% tt_end_tag %]
        [% tt_start_tag %] INCLUDE all_change [% tt_end_tag %]
        [% tt_start_tag %] x [% tt_end_tag %]			    # still '10'
        [% tt_start_tag %] y.z [% tt_end_tag %]			    # now 'zulu'

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.

        [% tt_start_tag %] BLOCK new_stuff [% tt_end_tag %]
           [% tt_start_tag %] # define a new 'y' hash array in local context
              y = { z => 'zulu' }
           [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

        [% tt_start_tag %] x = 10 [% tt_end_tag %]
        [% tt_start_tag %] INCLUDE new_stuff [% tt_end_tag %]
        [% tt_start_tag %] x [% tt_end_tag %]			    # outputs '10'
        [% tt_start_tag %] y [% tt_end_tag %]			    # nothing, y is undefined

Similarly, if you update an element of a compound variable which doesn't already exists then a hash will be created automatically and deleted again at the end of the block.

        [% tt_start_tag %] BLOCK new_stuff [% tt_end_tag %]
           [% tt_start_tag %] y.z = 'zulu' [% tt_end_tag %]
        [% tt_start_tag %] END [% tt_end_tag %]

However, if the hash does 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.

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.

        [% tt_start_tag %] global.version = 123 [% tt_end_tag %]

[%- END %] [% WRAPPER subsection title = 'Special Variables' -%]

A number of special variables are automatically defined by the Template Toolkit.

- template

  The 'template' variable contains a reference to the main template being processed, in the form of a Template::Document object. This variable is correctly defined within PRE_PROCESS, PROCESS and POST_PROCESS templates, allowing standard headers, footers, etc., to access metadata items from the main template. The 'name' and 'modtime' metadata items are automatically provided, giving the template name and modification time in seconds since the epoch.

  Note that the 'template' variable always references the top-level template, even when processing other template components via INCLUDE, PROCESS, etc.

- component

  The 'component' variable is like 'template' but always contains a reference to the current, innermost template component being processed. In the main template, the 'template' and 'component' variable will reference the same Template::Document object. In any other template component called from the main template, the 'template' variable will remain unchanged, but 'component' will contain a new reference to the current component.

  This example should demonstrate the difference:

          $template->process('foo')
      	|| die $template->error(), "\n";

  'foo':

          [% tt_start_tag %] template.name [% tt_end_tag %]		    # foo
          [% tt_start_tag %] component.name [% tt_end_tag %]	    # foo
          [% tt_start_tag %] PROCESS footer [% tt_end_tag %]

  'footer':

          [% tt_start_tag %] template.name [% tt_end_tag %]		    # foo
          [% tt_start_tag %] component.name [% tt_end_tag %]            # footer

- loop

  Within a FOREACH loop, the 'loop' variable references the Template::Iterator object responsible for controlling the loop.

          [% tt_start_tag %] FOREACH item = [ 'foo', 'bar', 'baz' ] -[% tt_end_tag %]
             [% tt_start_tag %] "Items:\n" IF loop.first -[% tt_end_tag %]
             [% tt_start_tag %] loop.count [% tt_end_tag %]/[% tt_start_tag %] loop.size [% tt_end_tag %]: [% tt_start_tag %] item [% tt_end_tag %]
          [% tt_start_tag %] END [% tt_end_tag %]

- error

  Within a CATCH block, the 'error' variable contains a reference to the Template::Exception object thrown from within the TRY block. The 'type' and 'info' methods can be called or the variable itself can be printed for automatic stringification into a message of the form "$type error - $info". See [% ttlink('Template::Exception') -%] for further details.

          [% tt_start_tag %] TRY [% tt_end_tag %]
             ...
          [% tt_start_tag %] CATCH [% tt_end_tag %]
             [% tt_start_tag %] error [% tt_end_tag %]
          [% tt_start_tag %] END [% tt_end_tag %]

- content

  The WRAPPER method captures the output from a template block and then includes a named template, passing the captured output as the 'content' variable.

          [% tt_start_tag %] WRAPPER box [% tt_end_tag %]
          Be not afeard; the isle is full of noises,
          Sounds and sweet airs, that give delight and hurt not.
          [% tt_start_tag %] END [% tt_end_tag %]

          [% tt_start_tag %] BLOCK box [% tt_end_tag %]
          <table border=1>
          <tr>
            <td>
            [% tt_start_tag %] content [% tt_end_tag %]
            </td>
          </tr>
          </table>
          [% tt_start_tag %] END [% tt_end_tag %]

[%- END %] [%- END %] [% WRAPPER section title='AUTHOR' -%]

Andy Wardley <abw@kfs.org>

[% ttlink('http://www.andywardley.com/', 'http://www.andywardley.com/') -%]

[%- END %] [% WRAPPER section title='VERSION' -%]

Template Toolkit version 2.06d, released on 22 January 2002.

[%- END %] [% WRAPPER section title='COPYRIGHT' -%]

      Copyright (C) 1996-2001 Andy Wardley.  All Rights Reserved.
      Copyright (C) 1998-2001 Canon Research Centre Europe Ltd.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

[%- END %]