ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- PK! ]RJJ Views.podnu6$#============================================================= -*-perl-*- # # Template::Manual::Views # # AUTHOR # Andy Wardley # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Views - Template Toolkit views (experimental) =head1 Overview A view is effectively a collection of templates and/or variable definitions which can be passed around as a self-contained unit. This then represents a particular interface or presentation style for other objects or items of data. You can use views to implement custom "skins" for an application or content set. You can use them to help simplify the presentation of common objects or data types. You can even use then to automate the presentation of complex data structures such as that generated in an C tree or similar. You let an iterator do the walking, and the view does the talking (or in this case, the presenting). Voila - you have view independent, structure shy traversal using templates. In general, views can be used in a number of different ways to achieve several different things. They elegantly solve some problems which were otherwise difficult or complicated, and make easy some things that were previously hard. At the moment, they're still very experimental. The directive syntax and underlying API are likely to change quite considerably over the next version or two. Please be very wary about building your multi-million dollar e-commerce solutions based around this feature. =head1 Views as Template Collectors/Providers The C directive starts a view definition and includes a name by which the view can be referenced. The view definition continues up to the matching C directive. [% VIEW myview %] ... [% END %] The first role of a view is to act as a collector and provider of templates. The C method can be called on a view to effectively do the same thing as the C directive. The template name is passed as the first argument, followed by any local variable definitions for the template. [% myview.include('header', title='The Title') %] # equivalent to [% INCLUDE header title='The Title' %] Views accept a number of configuration options which can be used to control different aspects of their behaviour. The 'C' and 'C' options can be specified to add a fixed prefix and/or suffix to the name of each template. [% VIEW myview prefix = 'my/' suffix = '.tt2' ; END %] Now the call [% myview.include('header', title='The Title') %] is equivalent to [% INCLUDE my/header.tt2 title='The Title' %] Views provide an C method which maps method names to the C method. Thus, the following are all equivalent: [% myview.include('header', title='Hello World') %] [% myview.include_header(title='Hello World') %] [% myview.header(title='Hello World') %] =head1 Local BLOCK Definitions A C definition can include C definitions which remain local to the view. A request for a particular template will return a C, if defined, in preference to any other template of the same name. [% BLOCK foo %] public foo block [% END %] [% VIEW plain %] [% BLOCK foo %] plain foo block [% END %] [% END %] [% VIEW fancy %] [% BLOCK foo %] fancy foo block [% END %] [% END %] [% INCLUDE foo %] # public foo block [% plain.foo %] # plain foo block [% fancy.foo %] # fancy foo block In addition to C definitions, a C can contain any other template directives. The entire C definition block is processed to initialise the view but no output is generated (this may change RSN - and get stored as 'C' item, subsequently accessible as C<[% view.output %]>). However, directives that have side-effects, such as those that update a variable, will have noticeable consequences. =head1 Preserving Variable State within Views Views can also be used to save the values of any existing variables, or to create new ones at the point at which the view is defined. Unlike simple template metadata (C) which can only contain static string values, the view initialisation block can contain any template directives and generate any kind of dynamic output and/or data items. [% VIEW my_web_site %] [% view.title = title or 'My Cool Web Site' %] [% view.author = "$abw.name, $abw.email" %] [% view.sidebar = INCLUDE my/sidebar.tt2 %] [% END %] Note that additional data items can be specified as arguments to the C directive. Anything that doesn't look like a configuration parameter is assumed to be a data item. This can be a little hazardous, of course, because you never know when a new configuration item might get added which interferes with your data. [% VIEW my_web_site # config options prefix = 'my/' # misc data title = title or 'My Cool Web Site' author = "$abw.name, $abw.email" sidebar = INCLUDE my/sidebar.tt2 %] ... [% END %] Outside of the view definition you can access the view variables as, for example: [% my_web_site.title %] One important feature is the equivalence of simple variables and templates. You can implement the view item 'C' as a simple variable, a template defined in an external file, possibly with a prefix/suffix automatically appended, or as a local C<BLOCK> definition within the C<[% VIEW %] ... [% END %]> definition. If you use the syntax above then the view will Do The Right Thing to return the appropriate output. At the C<END> of the C<VIEW> definition the view is "sealed" to prevent you from accidentally updating any variable values. If you attempt to change the value of a variable after the C<END> of the C<VIEW> definition block then a C<view> error will be thrown. [% TRY; my_web_site.title = 'New Title'; CATCH; error; END %] The error above will be reported as: view error - cannot update item in sealed view: title The same is true if you pass a parameter to a view variable. This is interpreted as an attempt to update the variable and will raise the same warning. [% my_web_site.title('New Title') %] # view error! You can set the C<silent> parameter to have the view ignore these parameters and simply return the variable value. [% VIEW my_web_site silent = 1 title = title or 'My Cool Web Site' # ... ; END %] [% my_web_site.title('Blah Blah') %] # My Cool Web Site Alternately, you can specify that a view is unsealed allowing existing variables to be updated and new variables defined. [% VIEW my_web_site sealed = 0 title = title or 'My Cool Web Site' # ... ; END %] [% my_web_site.title('Blah Blah') %] # Blah Blah [% my_web_site.title %] # Blah Blah =head2 Inheritance, Delegation and Reuse Views can be inherited from previously defined views by use of the C<base> parameter. This example shows how a base class view is defined which applies a C<view/default/> prefix to all template names. [% VIEW my.view.default prefix = 'view/default/'; END %] Thus the directive: [% my.view.default.header(title='Hello World') %] is now equivalent to: [% INCLUDE view/default/header title='Hello World' %] A second view can be defined which specifies the default view as a base. [% VIEW my.view.fancy base = my.view.default prefix = 'view/fancy/'; END %] Now the directive: [% my.view.fancy.header(title='Hello World') %] will resolve to: [% INCLUDE view/fancy/header title='Hello World' %] or if that doesn't exist, it will be handled by the base view as: [% INCLUDE view/default/header title='Hello World' %] When a parent view is specified via the C<base> parameter, the delegation of a view to its parent for fetching templates and accessing user defined variables is automatic. You can also implement your own inheritance, delegation or other reuse patterns by explicitly delegating to other views. [% BLOCK foo %] public foo block [% END %] [% VIEW plain %] [% BLOCK foo %] <plain>[% PROCESS foo %]</plain> [% END %] [% END %] [% VIEW fancy %] [% BLOCK foo %] [% plain.foo | replace('plain', 'fancy') %] [% END %] [% END %] [% plain.foo %] # <plain>public foo block</plain> [% fancy.foo %] # <fancy>public foo block</fancy> Note that the regular C<INCLUDE/PROCESS/WRAPPER> directives work entirely independently of views and will always get the original, unaltered template name rather than any local per-view definition. =head2 Self-Reference A reference to the view object under definition is available with the C<VIEW ... END> block by its specified name and also by the special name 'C<view>' (similar to the C<my $self = shift;> in a Perl method or the 'C<this>' pointer in C++, etc). The view is initially unsealed allowing any data items to be defined and updated within the C<VIEW ... END> block. The view is automatically sealed at the end of the definition block, preventing any view data from being subsequently changed. (NOTE: sealing should be optional. As well as sealing a view to prevent updates (C<SEALED>), it should be possible to set an option in the view to allow external contexts to update existing variables (C<UPDATE>) or even create totally new view variables (C<CREATE>)). [% VIEW fancy %] [% fancy.title = 'My Fancy Title' %] [% fancy.author = 'Frank Open' %] [% fancy.col = { bg => '#ffffff', bar => '#a0a0ff' } %] [% END %] or [% VIEW fancy %] [% view.title = 'My Fancy Title' %] [% view.author = 'Frank Open' %] [% view.col = { bg => '#ffffff', bar => '#a0a0ff' } %] [% END %] It makes no real difference in this case if you refer to the view by its name, 'C<fancy>', or by the general name, 'C<view>'. Outside of the view block, however, you should always use the given name, 'C<fancy>': [% fancy.title %] [% fancy.author %] [% fancy.col.bg %] The choice of given name or 'C<view>' is much more important when it comes to C<BLOCK> definitions within a C<VIEW>. It is generally recommended that you use 'C<view>' inside a C<VIEW> definition because this is guaranteed to be correctly defined at any point in the future when the block gets called. The original name of the view might have long since been changed or reused but the self-reference via 'C<view>' should always be intact and valid. Take the following VIEW as an example: [% VIEW foo %] [% view.title = 'Hello World' %] [% BLOCK header %] Title: [% view.title %] [% END %] [% END %] Even if we rename the view, or create a new C<foo> variable, the header block still correctly accesses the C<title> attribute of the view to which it belongs. Whenever a view C<BLOCK> is processed, the C<view> variable is always updated to contain the correct reference to the view object to which it belongs. [% bar = foo %] [% foo = { title => "New Foo" } %] # no problem [% bar.header %] # => Title: Hello World =head2 Saving References to External Views When it comes to view inheritance, it's always a good idea to take a local copy of a parent or delegate view and store it as an attribute within the view for later use. This ensures that the correct view reference is always available, even if the external name of a view has been changed. [% VIEW plain %] ... [% END %] [% VIEW fancy %] [% view.plain = plain %] [% BLOCK foo %] [% view.plain.foo | replace('plain', 'fancy') %] [% END %] [% END %] [% plain.foo %] # => <plain>public foo block</plain> [% plain = 'blah' %] # no problem [% fancy.foo %] # => <fancy>public foo block</fancy> =head2 Views as Data Presenters Another key role of a view is to act as a dispatcher to automatically apply the correct template to present a particular object or data item. This is handled via the C<print()> method. Here's an example: [% VIEW foo %] [% BLOCK text %] Some text: [% item %] [% END %] [% BLOCK hash %] a hash: [% FOREACH key = item.keys.sort -%] [% key %] => [% item.$key %] [% END -%] [% END %] [% BLOCK list %] a list: [% item.sort.join(', ') %] [% END %] [% END %] We can now use the view to print text, hashes or lists. The C<print()> method includes the right template depending on the typing of the argument (or arguments) passed. [% some_text = 'I read the news today, oh boy.' %] [% a_hash = { house => 'Lords', hall => 'Albert' } %] [% a_list = [ 'sure', 'Nobody', 'really' ] %] [% view.print(some_text) %] # Some text: I read the news today, oh boy. [% view.print(a_hash) %] # a hash: hall => Albert house => Lords [% view.print(a_list) %] # a list: Nobody, really, sure You can also provide templates to print objects of any other class. The class name is mapped to a template name with all non-word character sequences such as 'C<::>' converted to a single 'C<_>'. [% VIEW foo %] [% BLOCK Foo_Bar %] a Foo::Bar object: thingies: [% view.print(item.thingies) %] doodahs: [% view.print(item.doodahs) %] [% END %] [% END %] [% USE fubar = Foo::Bar(...) %] [% foo.print(fubar) %] Note how we use the view object to display various items within the objects ('C<thingies>' and 'C<doodahs>'). We don't need to worry what kind of data these represent (text, list, hash, etc) because we can let the view worry about it, automatically mapping the data type to the correct template. Views may define their own type =E<gt> template map. [% VIEW foo map = { TEXT => 'plain_text', ARRAY => 'show_list', HASH => 'show_hash', My::Module => 'template_name' default => 'any_old_data' } %] [% BLOCK plain_text %] ... [% END %] ... [% END %] They can also provide a C<default> map entry, specified as part of the C<map> hash or as a parameter by itself. [% VIEW foo map = { ... }, default = 'whatever' %] ... [% END %] or [% VIEW foo %] [% view.map = { ... } view.default = 'whatever' %] ... [% END %] The C<print()> method provides one more piece of magic. If you pass it a reference to an object which provides a C<present()> method, then the method will be called passing the view as an argument. This then gives any object a chance to determine how it should be presented via the view. package Foo::Bar; ... sub present { my ($self, $view) = @_; return "a Foo::Bar object:\n" . "thingies: " . $view->print($self->{ _THINGIES }) . "\n" . "doodahs: " . $view->print($self->{ _DOODAHS }) . "\n"; } The object is free to delve deeply into its innards and mess around with its own private data, before presenting the relevant data via the view. In a more complex example, a C<present()> method might walk part of a tree making calls back against the view to present different nodes within the tree. We may not want to expose the internal structure of the tree (because that would break encapsulation and make our presentation code dependant on it) but we want to have some way of walking the tree and presenting items found in a particular manner. This is known as I<Structure Shy Traversal>. Our view object doesn't require prior knowledge about the internal structure of any data set to be able to traverse it and present the data contained therein. The data items themselves, via the C<present()> method, can implement the internal iterators to guide the view along the right path to presentation happiness. The upshot is that you can use views to greatly simplify the display of data structures like C<XML::DOM> trees. The documentation for the C<Template::Plugin::XML::DOM> module contains an example of this. In essence, it looks something like this: XML source: <user name="Andy Wardley"> <project id="iCan" title="iCan, but theyCan't"/> <project id="p45" title="iDid, but theyDidn't"/> </user> TT View: [% VIEW fancy %] [% BLOCK user %] User: [% item.name %] [% item.content(myview) %] [% END %] [% BLOCK project %] Project: [% project.id %] - [% project.name %] [% END %] [% END %] Generate view: [% USE dom = XML.DOM %] [% fancy.print(dom.parse(xml_source)) %] Output: User: Andy Wardley Project: iCan - iCan, but theyCan't Project: p45 - iDid, but theyDidn't The same approach can be applied to many other areas. Here's an example from the C<File>/C<Directory> plugins. [% VIEW myview %] [% BLOCK file %] - [% item.name %] [% END %] [% BLOCK directory %] * [% item.name %] [% item.content(myview) FILTER indent %] [% END %] [% END %] [% USE dir = Directory(dirpath) %] [% myview.print(dir) %] And here's the same approach use to convert POD documentation to any other format via template. [% # load Pod plugin and parse source file into Pod Object Model USE Pod; pom = Pod.parse_file(my_pod_file); # define view to map all Pod elements to "pod/html/xxx" templates VIEW pod2html prefix='pod/html'; END; # now print document via view (i.e. as HTML) pod2html.print(pom) %] Here we simply define a template prefix for the view which causes the view to look for C<pod/html/head1>, C<pod/html/head2>, C<pod/html/over> as templates to present the different sections of the parsed Pod document. There are some examples in the Template Toolkit test suite: F<t/pod.t> and F<t/view.t> which may shed some more light on this. See the distribution sub-directory F<examples/pod/html> for examples of Pod -E<gt> HTML templates. =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ]v#��#�� ��Syntax.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::Syntax # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Syntax - Directive syntax, structure and semantics =head1 Tag Styles Template directives are embedded between start and end markers tags. By default these tag markers are C<[%> and C<%]>. [% PROCESS header %] <h1>Hello World!</h1> <a href="[% page.next %]"><img src="[% icon.next %].gif"></a> [% PROCESS footer %] You can change the tag characters using the C<START_TAG>, C<END_TAG> and C<TAG_STYLE> configuration options. You can also use the C<TAGS> directive to define a new tag style for the current template file. You can also set the C<INTERPOLATE> option to allow simple variable references to be embedded directly in templates, prefixed by a C<$>. # INTERPOLATE = 0 <td>[% name %]</td> <td>[% email %]</td> # INTERPOLATE = 1 <td>$name</td> <td>$email</td> Directives may be embedded anywhere in a line of text and can be split across several lines. Insignificant whitespace is generally ignored within the directive. [% INCLUDE header title = 'Hello World' bgcol = '#ffffff' %] [%INCLUDE menu align='right'%] Name: [% name %] ([%id%]) =head1 Outline Tags As of version 2.26, the Template Toolkit supports "outline" tags. These have a designated marker at the start of a line (C<%%> by default) and continue to the end of a line. The newline character at the end of the line is discarded (aka "chomped"). So rather than writing something like this: [% IF some.list.size -%] <ul> [% FOREACH item IN some.list -%] <li>[% item.html %]</li> [% END -%] </ul> [% END -%] You can write it like this instead: %% IF some.list.size <ul> %% FOREACH item IN some.list <li>[% item.html %]</li> %% END </ul> %% END Outline tags aren't enabled by default. There are a numbers of ways you can enable them. The first is to use the C<TAGS> directive to set the tag style to C<outline> in any templates where you want to use them. This will enable outline tags from that point on. [% TAGS outline -%] %% INCLUDE header You can set the C<TAGS> back to the C<default> value at some point later in the template if you want to disable them: [% TAGS default -%] You can set the C<TAG_STYLE> configuration option if you want then enabled in all templates by default. You can always use the C<[% TAGS default %]> directive to disable them in any templates or parts of templates if necessary. my $tt = Template->new({ TAG_STYLE => 'outline', }); The C<OUTLINE_TAG> option allows you to set the outline tag marker to something else if you're not a fan of percent signs. Setting this option will automatically enable outline tags. my $tt = Template->new({ OUTLINE_TAG => '>>', }); You can also use the C<TAGS> directive to define your own custom tags (start, end and now optionally, outline) for a template or part of a template. [% TAGS <* *> >> %] >> INCLUDE header # outline tag Hello <* name *> # inline tag If you only specify a start and end tag then outline tags will be disabled. [% TAGS <* *> %] # no outline tags =head1 Comments The C<#> character is used to indicate comments within a directive. When placed immediately inside the opening directive tag, it causes the entire directive to be ignored. [%# this entire directive is ignored no matter how many lines it wraps onto %] In any other position, it causes the remainder of the current line to be treated as a comment. [% # this is a comment theta = 20 # so is this rho = 30 # <aol>me too!</aol> %] =head1 Chomping Whitespace You can add C<-> or C<+> to the immediate start or end of a directive tag to control the whitespace chomping options. See the C<PRE_CHOMP> and C<POST_CHOMP> options for further details. [% BLOCK foo -%] # remove trailing newline This is block foo [%- END %] # remove leading newline =head1 Implicit Directives: GET and SET The simplest directives are C<GET> and C<SET> which retrieve and update variable values respectively. The C<GET> and C<SET> keywords are actually optional as the parser is smart enough to see them for what they really are (but note the caveat below on using side-effect notation). Thus, you'll generally see: [% SET foo = 10 %] [% GET foo %] written as: [% foo = 10 %] [% foo %] You can also express simple logical statements as implicit C<GET> directives: [% title or template.title or 'Default Title' %] [% mode == 'graphics' ? "Graphics Mode Enabled" : "Text Mode" %] All other directives should start with a keyword specified in UPPER CASE (but see the C<ANYCASE> option). All directives keywords are in UPPER CASE to make them visually distinctive and to distinguish them from variables of the same name but different case. It is perfectly valid, for example, to define a variable called C<stop> which is entirely separate from the C<STOP> directive. [% stop = 'Clackett Lane Bus Depot' %] The bus will next stop at [% stop %] # variable [% STOP %] # directive =head1 Block Directives Directives such as C<FOREACH>, C<WHILE>, C<BLOCK>, C<FILTER>, etc., mark the start of a block which may contain text or other directives up to the matching C<END> directive. Blocks may be nested indefinitely. The C<IF>, C<UNLESS>, C<ELSIF> and C<ELSE> directives also define blocks and may be grouped together in the usual manner. [% FOREACH item = [ 'foo' 'bar' 'baz' ] %] * Item: [% item %] [% END %] [% BLOCK footer %] Copyright 2000 [% me %] [% INCLUDE company/logo %] [% END %] [% IF foo %] [% FOREACH thing = foo.things %] [% thing %] [% END %] [% ELSIF bar %] [% INCLUDE barinfo %] [% ELSE %] do nothing... [% END %] Block directives can also be used in a convenient side-effect notation. [% INCLUDE userinfo FOREACH user = userlist %] [% INCLUDE debugtxt msg="file: $error.info" IF debugging %] [% "Danger Will Robinson" IF atrisk %] versus: [% FOREACH user = userlist %] [% INCLUDE userinfo %] [% END %] [% IF debugging %] [% INCLUDE debugtxt msg="file: $error.info" %] [% END %] [% IF atrisk %] Danger Will Robinson [% END %] =head1 Capturing Block Output The output of a directive can be captured by simply assigning the directive to a variable. [% headtext = PROCESS header title="Hello World" %] [% people = PROCESS userinfo FOREACH user = userlist %] This can be used in conjunction with the C<BLOCK> directive for defining large blocks of text or other content. [% poem = BLOCK %] The boy stood on the burning deck, His fleece was white as snow. A rolling stone gathers no moss, And Keith is sure to follow. [% END %] Note one important caveat of using this syntax in conjunction with side-effect notation. The following directive does not behave as might be expected: [% var = 'value' IF some_condition %] # does not work In this case, the directive is interpreted as (spacing added for clarity) [% var = IF some_condition %] value [% END %] rather than [% IF some_condition %] [% var = 'value' %] [% END %] The variable is assigned the output of the C<IF> block which returns C<'value'> if true, but nothing if false. In other words, the following directive will always cause 'var' to be cleared. [% var = 'value' IF 0 %] To achieve the expected behaviour, the directive should be written as: [% SET var = 'value' IF some_condition %] =head1 Chaining Filters Multiple C<FILTER> directives can be chained together in sequence. They are called in the order defined, piping the output of one into the input of the next. [% PROCESS somefile FILTER truncate(100) FILTER html %] The pipe character, C<|>, can also be used as an alias for C<FILTER>. [% PROCESS somefile | truncate(100) | html %] =head1 Multiple Directive Blocks Multiple directives can be included within a single tag when delimited by semi-colons. Note however that the C<TAGS> directive must always be specified in a tag by itself. [% IF title; INCLUDE header; ELSE; INCLUDE other/header title="Some Other Title"; END %] versus [% IF title %] [% INCLUDE header %] [% ELSE %] [% INCLUDE other/header title="Some Other Title" %] [% END %] =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ]Je5b��5b�� ��Variables.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::Variables # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Variables - Template variables and code bindings =head1 Template Variables A reference to a hash array may be passed as the second argument to the L<process()|Template#process()> method, containing definitions of template variables. The C<VARIABLES> (a.k.a. C<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); F<myfile> template: This is version [% version %] ([% release %]). Serial number: [% serial_no %] Generated 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 I<is> significant however, and 'C<foo>', 'C<Foo>' and 'C<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 data: 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'), }; Example template: [% article %] [% person.id %]: [% person.name %] <[% person.email %]> [% primes.first %] - [% primes.last %], including [% primes.3 %] [% primes.size %] prime numbers: [% primes.join(', ') %] [% wizard %] [% wizard('Hocus Pocus!') %] [% cgi.param('mode') %] Generated 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 =head2 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. [% article %] =head2 Hash Array References Members of hash arrays are accessed by specifying the hash reference and key separated by the dot 'C<.>' operator. Example data: my $vars = { 'home' => 'http://www.myserver.com/homepage.html', 'page' => { 'this' => 'mypage.html', 'next' => 'nextpage.html', 'prev' => 'prevpage.html', }, }; Example template: <a href="[% home %]">Home</a> <a href="[% page.prev %]">Previous Page</a> <a href="[% page.next %]">Next Page</a> Generated 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 'C<_>' or 'C<.>' 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 C<DEBUG> option is enabled). Example data: my $vars = { message => 'Hello World!', _secret => "On the Internet, no-one knows you're a dog", thing => { public => 123, _private => 456, '.hidden' => 789, }, }; Example template: [% message %] # outputs "Hello World!" [% _secret %] # no output [% thing.public %] # outputs "123" [% thing._private %] # no output [% thing..hidden %] # ERROR: unexpected token (..) You can disable this feature by setting the C<$Template::Stash::PRIVATE> package variable to a false value. $Template::Stash::PRIVATE = undef; # now you can thing._private To access a hash entry using a key stored in another variable, prefix the key variable with 'C<$>' to have it interpolated before use (see L<Variable Interpolation>). [% pagename = 'next' %] [% page.$pagename %] # same as [% page.next %] You can also access hash entry using C<item()> method. This might be helpful if you have complex key name. <pre> [% files.item('example.txt').content %] </pre> See L<Template::Manual::VMethods|Template::Manual::VMethods/"item"> for more info. When you assign to a variable that contains multiple namespace elements (i.e. it has one or more 'C<.>' characters in the name), any hashes required to represent intermediate namespaces will be created automatically. In this following example, the C<product> variable automatically springs into life as a hash array unless otherwise defined. [% product.id = 'XYZ-2000' product.desc = 'Bogon Generator' product.price = 666 %] The [% product.id %] [% product.desc %] costs $[% product.price %].00 Generated output: The XYZ-2000 Bogon Generator costs $666.00 You can use Perl's familiar C<{> ... C<}> construct to explicitly create a hash and assign it to a variable. Note that commas are optional between key/value pairs and C<=> can be used in place of C<=E<gt>>. # minimal TT style [% product = { id = 'XYZ-2000' desc = 'Bogon Generator' price = 666 } %] # perl style [% product = { id => 'XYZ-2000', desc => 'Bogon Generator', price => 666, } %] =head2 List References Items in lists are also accessed by use of the dot operator. Example data: my $vars = { people => [ 'Tom', 'Dick', 'Larry' ], }; Example template: [% people.0 %] # Tom [% people.1 %] # Dick [% people.2 %] # Larry The C<FOREACH> directive can be used to iterate through items in a list. [% FOREACH person IN people %] Hello [% person %] [% END %] Generated output: Hello Tom Hello Dick Hello Larry Lists can be constructed in-situ using the regular anonymous list C<[> ... C<]> construct. Commas between items are optional. [% cols = [ 'red', 'green', 'blue' ] %] [% FOREACH c IN cols %] [% c %] [% END %] or: [% FOREACH c IN [ 'red', 'green', 'blue' ] %] [% c %] [% END %] You can also create simple numerical sequences using the C<..> range operator: [% n = [ 1 .. 4 ] %] # n is [ 1, 2, 3, 4 ] [% x = 4 y = 8 z = [x..y] # z is [ 4, 5, 6, 7, 8 ] %] =head2 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!', @_) }, }; Example template: [% wizard %] # Abracadabra! [% wizard('Hocus Pocus!') %] # Abracadabra! Hocus Pocus! =head2 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'), }; Example template: [% FOREACH p IN cgi.param %] # returns list of param keys [% p %] => [% cgi.param(p) %] # fetch each param value [% END %] Generated 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. [% myobj.method = 10 %] equivalent to: [% myobj.method(10) %] =head2 Passing Parameters and Returning 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: [% foo = 10 %] [% mycode(foo, 20) %] # 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 B<last> parameter to the sub-routine. Named parameters can be specified using either C<=E<gt>> or C<=> 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 } || ' + ', @_); } Example template: [% myjoin(10, 20, 30) %] [% myjoin(10, 20, 30, joint = ' - ' %] [% myjoin(joint => ' * ', 10, 20, 30 %] Generated 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. [% r = 'Romeo' %] [% r(100, 99, s, t, v) %] # 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' ) }, }; Example template: [% FOREACH i IN items1 %] ... [% END %] [% FOREACH i IN items2 %] ... [% END %] =head2 Error Handling Errors can be reported from user code by calling C<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 C<error> variable. my $vars = { barf => sub { die "a sick error has occurred\n"; }, }; Example template: [% TRY %] [% barf %] # calls sub which throws error via die() [% CATCH %] [% error.info %] # outputs "a sick error has occurred\n" [% END %] Error messages thrown via C<die()> are converted to exceptions of type C<undef> (the literal string "undef" rather than the undefined value). Exceptions of user-defined types can be thrown by calling C<die()> with a reference to a L<Template::Exception> object. use Template::Exception; my $vars = { login => sub { ...do something... die Template::Exception->new( badpwd => 'password too silly' ); }, }; Example template: [% TRY %] [% login %] [% CATCH badpwd %] Bad password: [% error.info %] [% CATCH %] Some other '[% error.type %]' error: [% error.info %] [% END %] The exception types C<stop> and C<return> are used to implement the C<STOP> and C<RETURN> directives. Throwing an exception as: die (Template::Exception->new('stop')); has the same effect as the directive: [% STOP %] =head1 Virtual Methods The Template Toolkit implements a number of "virtual methods" which can be applied to scalars, hashes or lists. For example: [% mylist = [ 'foo', 'bar', 'baz' ] %] [% newlist = mylist.sort %] Here C<mylist> 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: [% mylist.sort.join(', ') %] Here the C<join> virtual method is called to join the sorted list into a single string, generating the following output: bar, baz, foo See L<Template::Manual::VMethods> for details of all the virtual methods available. =head1 Variable Interpolation The Template Toolkit uses C<$> consistently to indicate that a variable should be interpolated in position. Most frequently, you see this in double-quoted strings: [% fullname = "$honorific $firstname $surname" %] Or embedded in plain text when the C<INTERPOLATE> option is set: Dear $honorific $firstname $surname, The same rules apply within directives. If a variable is prefixed with a C<$> 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. [% uid = 'abw' %] [% users.$uid %] # same as 'users.abw' Curly braces can be used to delimit interpolated variable names where necessary. [% users.${me.id}.name %] Directives such as C<INCLUDE>, C<PROCESS>, etc., that accept a template name as the first argument, will automatically quote it for convenience. [% INCLUDE foo/bar.txt %] The above example is equivalent to: [% INCLUDE "foo/bar.txt" %] To C<INCLUDE> a template whose name is stored in a variable, simply prefix the variable name with C<$> to have it interpolated. [% myfile = 'header' %] [% INCLUDE $myfile %] This is equivalent to: [% INCLUDE header %] Note also that a variable containing a reference to a L<Template::Document> object can also be processed in this way. my $vars = { header => Template::Document->new({ ... }), }; Example template: [% INCLUDE $header %] =head1 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 C<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 C<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. [% BLOCK change_name %] [% name = 'bar' %] [% END %] [% name = 'foo' %] [% INCLUDE change_name %] [% name %] # foo [% PROCESS change_name %] [% name %] # 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. [% BLOCK all_change %] [% x = 20 %] # changes copy [% y.z = 'zulu' %] # changes original [% END %] [% x = 10 y = { z => 'zebra' } %] [% INCLUDE all_change %] [% x %] # still '10' [% y.z %] # 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. [% BLOCK new_stuff %] [% # define a new 'y' hash array in local context y = { z => 'zulu' } %] [% END %] [% x = 10 %] [% INCLUDE new_stuff %] [% x %] # outputs '10' [% y %] # nothing, y is undefined Similarly, if you update an element of a compound variable which I<doesn't> already exists then a hash will be created automatically and deleted again at the end of the block. [% BLOCK new_stuff %] [% y.z = 'zulu' %] [% END %] However, if the hash I<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. [% global.version = 123 %] =head1 Compile Time Constant Folding 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. To define compile-time constants, specify a C<CONSTANTS> hash as a constructor item as per C<VARIABLES>. The C<CONSTANTS> hash can contain any kind of complex, nested, or dynamic data structures, just like regular variables. my $tt = Template->new({ CONSTANTS => { version => 3.14, release => 'skyrocket', col => { back => '#ffffff', fore => '#000000', }, myobj => My::Object->new(), mysub => sub { ... }, joint => ', ', }, }); Within a template, you access these variables using the C<constants> namespace prefix. Version [% constants.version %] ([% constants.release %]) Background: [% constants.col.back %] 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. You can call subroutines, object methods, and even virtual methods on constant variables. [% constants.mysub(10, 20) %] [% constants.myobj(30, 40) %] [% constants.col.keys.sort.join(', ') %] One important proviso is that any arguments you pass to subroutines or methods must also be literal values or compile time constants. For example, these are both fine: # literal argument [% constants.col.keys.sort.join(', ') %] # constant argument [% constants.col.keys.sort.join(constants.joint) %] But this next example will raise an error at parse time because C<joint> is a runtime variable and cannot be determined at compile time. # ERROR: runtime variable argument! [% constants.col.keys.sort.join(joint) %] The C<CONSTANTS_NAMESPACE> option can be used to provide a different namespace prefix for constant variables. For example: my $tt = Template->new({ CONSTANTS => { version => 3.14, # ...etc... }, CONSTANTS_NAMESPACE => 'const', }); Constants would then be referenced in templates as: [% const.version %] =head1 Special Variables A number of special variables are automatically defined by the Template Toolkit. =head2 template The C<template> variable contains a reference to the main template being processed, in the form of a L<Template::Document> object. This variable is correctly defined within C<PRE_PROCESS>, C<PROCESS> and C<POST_PROCESS> templates, allowing standard headers, footers, etc., to access metadata items from the main template. The C<name> and C<modtime> metadata items are automatically provided, giving the template name and modification time in seconds since the epoch. Note that the C<template> variable always references the top-level template, even when processing other template components via C<INCLUDE>, C<PROCESS>, etc. =head2 component The C<component> variable is like C<template> but always contains a reference to the current, innermost template component being processed. In the main template, the C<template> and C<component> variable will reference the same L<Template::Document> object. In any other template component called from the main template, the C<template> variable will remain unchanged, but C<component> will contain a new reference to the current component. This example should demonstrate the difference: $template->process('foo') || die $template->error(), "\n"; F<foo> template: [% template.name %] # foo [% component.name %] # foo [% PROCESS footer %] F<footer> template: [% template.name %] # foo [% component.name %] # footer Additionally, the C<component> variable has two special fields: C<caller> and C<callers>. C<caller> contains the name of the template that called the current template (or undef if the values of C<template> and C<component> are the same). C<callers> 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. Here's an example: F<outer.tt2> template: [% component.name %] # 'outer.tt2' [% component.caller %] # undef [% component.callers %] # undef [% PROCESS 'middle.tt2' %] F<middle.tt2> template: [% component.name %] # 'middle.tt2' [% component.caller %] # 'outer.tt2' [% component.callers %] # [ 'outer.tt2' ] [% PROCESS 'inner.tt2' %] F<inner.tt2> template: [% component.name %] # 'inner.tt2' [% component.caller %] # 'middle.tt2' [% component.callers %] # [ 'outer.tt2', 'middle.tt2' ] =head2 loop Within a C<FOREACH> loop, the C<loop> variable references the L<Template::Iterator> object responsible for controlling the loop. [% FOREACH item = [ 'foo', 'bar', 'baz' ] -%] [% "Items:\n" IF loop.first -%] [% loop.count %]/[% loop.size %]: [% item %] [% END %] =head2 error Within a C<CATCH> block, the C<error> variable contains a reference to the L<Template::Exception> object thrown from within the C<TRY> block. The C<type> and C<info> methods can be called or the variable itself can be printed for automatic stringification into a message of the form "C<$type error - $info>". See L<Template::Exception> for further details. [% TRY %] ... [% CATCH %] [% error %] [% END %] =head2 content The C<WRAPPER> method captures the output from a template block and then includes a named template, passing the captured output as the 'content' variable. [% WRAPPER box %] Be not afeard; the isle is full of noises, Sounds and sweet airs, that give delight and hurt not. [% END %] [% BLOCK box %] <blockquote class="prose"> [% content %] </blockquote> [% END %] =head1 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. [% myorg.people.sort('surname').first.fullname %] Intermediate variables may be used and will behave entirely as expected. [% sorted = myorg.people.sort('surname') %] [% sorted.first.fullname %] 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. =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ] ܑ%��%�� ��Intro.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::Intro # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Intro - Introduction to the Template Toolkit =head1 Introduction The Template Toolkit is a collection of Perl modules which implement a fast, flexible, powerful and extensible template processing system. It is most often used for generating dynamic web content, although it can be used equally well for processing any kind of text documents. At the simplest level it provides an easy way to process template files, filling in embedded variable references with their equivalent values. Here's an example of a template. Dear [% name %], It has come to our attention that your account is in arrears to the sum of [% debt %]. Please settle your account before [% deadline %] or we will be forced to revoke your Licence to Thrill. The Management. By default, template directives are embedded within the character sequences C<[%> ... C<%]> but you can change these and various other options to configure how the Template Toolkit looks, feels and works. You can set the C<INTERPOLATE> option, for example, if you prefer to embed your variables in Perl style: Dear $name, It has come to our attention that your account is in arrears to the sum of $debt. ...etc... =head1 The Template Perl Module The L<Template> Perl module is the front end to the Template Toolkit for Perl programmers, providing access to the full range of functionality through a single module with a simple interface. It loads the other modules as required and instantiates a default set of objects to handle subsequent template processing requests. Configuration parameters may be passed to the L<Template> constructor method, L<new()|Template#new()>, which are then used to configure the generate object. use Template; my $tt = Template->new({ INCLUDE_PATH => '/usr/local/templates', INTERPOLATE => 1, }) || die "$Template::ERROR\n"; The L<Template> object implements a L<process()|Template#process()> method for processing template files or text. The name of the input template (or various other sources) is passed as the first argument, followed by a reference to a hash array of variable definitions for substitution in the template. my $vars = { name => 'Count Edward van Halen', debt => '3 riffs and a solo', deadline => 'the next chorus', }; $tt->process('letters/overdrawn', $vars) || die $tt->error(), "\n"; The L<process()|Template#process()> method returns a true value (C<1>) on success and prints the template output to C<STDOUT>, by default. On error, the L<process()|Template#process()> method returns a false value (C<undef>). The L<error()|Template#error()> method can then be called to retrieve details of the error. =head1 Component Based Content Construction A number of special directives are provided, such as C<INSERT>, C<INCLUDE> and C<PROCESS>, which allow content to be built up from smaller template components. This permits a modular approach to building a web site or other content repository, promoting reusability, cross-site consistency, ease of construction and subsequent maintenance. Common elements such as headers, footers, menu bars, tables, and so on, can be created as separate template files which can then be processed into other documents as required. All defined variables are inherited by these templates along with any additional "local" values specified. [% PROCESS header title = "The Cat Sat on the Mat" %] [% PROCESS menu %] The location of the missing feline has now been established. Thank you for your assistance. [% INSERT legal/disclaimer %] [% PROCESS footer %] You can also define a template as a BLOCK within the same file and PROCESS it just like any other template file. This can be invaluable for building up repetitive elements such as tables, menus, etc. [% BLOCK tabrow %] <tr><td>[% name %]</td><td>[% email %]</td></tr> [% END %] <table> [% PROCESS tabrow name="tom" email="tom@here.org" %] [% PROCESS tabrow name="dick" email="disk@there.org" %] [% PROCESS tabrow name="larry" email="larry@where.org" %] </table> =head1 Data and Code Binding One of the key features that sets the Template Toolkit apart from other template processors is the ability to bind template variables to any kind of Perl data: scalars, lists, hash arrays, sub-routines and objects. my $vars = { root => 'http://here.com/there', menu => [ 'modules', 'authors', 'scripts' ], client => { name => 'Doctor Joseph von Satriani', id => 'JVSAT', }, checkout => sub { my $total = shift; ...; return $something }, shopcart => My::Cool::Shopping::Cart->new(), }; The Template Toolkit will automatically Do The Right Thing to access the data in an appropriate manner to return some value which can then be output. The dot operator 'C<.>' is used to access into lists and hashes or to call object methods. The C<FOREACH> directive is provided for iterating through lists, and various logical tests are available using directives such as C<IF>, C<UNLESS>, C<ELSIF>, C<ELSE>, C<SWITCH>, C<CASE>, etc. [% FOREACH section = menu %] <a href="[% root %]/[% section %]/index.html">[% section %]</a> [% END %] <b>Client</b>: [% client.name %] (id: [% client.id %]) [% IF shopcart.nitems %] Your shopping cart contains the following items: <ul> [% FOREACH item = shopcart.contents %] <li>[% item.name %] : [% item.qty %] @ [% item.price %] [% END %] </ul> [% checkout(shopcart.total) %] [% ELSE %] No items currently in shopping cart. [% END %] =head1 Advanced Features: Filters, Macros, Exceptions, Plugins The Template Toolkit also provides a number of additional directives for advanced processing and programmatical functionality. It supports output filters (FILTER), allows custom macros to be defined (MACRO), has a fully-featured exception handling system (TRY, THROW, CATCH, FINAL) and supports a plugin architecture (USE) which allows special plugin modules and even regular Perl modules to be loaded and used with the minimum of fuss. The Template Toolkit is "just" a template processor but you can trivially extend it to incorporate the functionality of any Perl module you can get your hands on. Thus, it is also a scalable and extensible template framework, ideally suited for managing the presentation layer for application servers, content management systems and other web applications. =head1 Separating Presentation and Application Logic Rather than embedding Perl code or some other scripting language directly into template documents, it encourages you to keep functional components (i.e. Perl code) separate from presentation components (e.g. HTML templates). The template variables provide the interface between the two layers, allowing data to be generated in code and then passed to a template component for displaying (pipeline model) or for sub-routine or object references to be bound to variables which can then be called from the template as and when required (callback model). The directives that the Template Toolkit provide implement their own mini programming language, but they're not really designed for serious, general purpose programming. Perl is a far more appropriate language for that. If you embed application logic (e.g. Perl or other scripting language fragments) in HTML templates then you risk losing the clear separation of concerns between functionality and presentation. It becomes harder to maintain the two elements in isolation and more difficult, if not impossible, to reuse code or presentation elements by themselves. It is far better to write your application code in separate Perl modules, libraries or scripts and then use templates to control how the resulting data is presented as output. Thus you should think of the Template Toolkit language as a set of layout directives for displaying data, not calculating it. Having said that, the Template Toolkit doesn't force you into one approach or the other. It attempts to be pragmatic rather than dogmatic in allowing you to do whatever best gets the job done. Thus, if you enable the EVAL_PERL option then you can happily embed real Perl code in your templates within PERL ... END directives. =head1 Performance The Template Toolkit uses a fast YACC-like parser which compiles templates into Perl code for maximum runtime efficiency. It also has an advanced caching mechanism which manages in-memory and on-disk (i.e. persistent) versions of compiled templates. The modules that comprise the toolkit are highly configurable and the architecture around which they're built is designed to be extensible. The Template Toolkit provides a powerful framework around which content creation and delivery systems can be built while also providing a simple interface through the Template front-end module for general use. =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ]2\G��\G�� ��Internals.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::Internals # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Internals - Template Toolkit internals =head1 Introduction This section of the documentation is aimed at developers wishing to know more about how the Template Toolkit works on the inside in order to extend or adapt it to their own needs. If that doesn't sound like you then you probably don't need to read this. There is no test afterwards. =head1 Outside Looking In The L<Template> module is simply a front end module which creates and uses a L<Template::Service> and pipes the output wherever you want it to go (C<STDOUT> by default, or maybe a file, scalar, etc). The C<Apache::Template> module (available separately from CPAN) is another front end. That creates a C<Template::Service::Apache> object, calls on it as required and sends the output back to the relevant C<Apache::Request> object. These front-end modules are really only there to handle any specifics of the environment in which they're being used. The C<Apache::Template> front end, for example, handles C<Apache::Request> specifics and configuration via the F<httpd.conf>. The regular L<Template> front-end deals with C<STDOUT>, variable refs, etc. Otherwise it is L<Template::Service> (or subclass) which does all the work. The L<Template::Service> module provides a high-quality template delivery service, with bells, whistles, signed up service level agreement and a 30-day no quibble money back guarantee. "Have a good time, all the time", that's our motto. Within the lower levels of the Template Toolkit, there are lots of messy details that we generally don't want to have to worry about most of the time. Things like templates not being found, or failing to parse correctly, uncaught exceptions being thrown, missing plugin modules or dependencies, and so on. L<Template::Service> hides that all away and makes everything look simple to the outsider. It provides extra features, like C<PRE_PROCESS>, C<PROCESS> and C<POST_PROCESS>, and also provides the error recovery mechanism via C<ERROR>. You ask it to process a template and it takes care of everything for you. The C<Template::Service::Apache> module goes a little bit further, adding some extra headers to the L<Apache::Request>, setting a few extra template variables, and so on. For the most part, the job of a service is really just one of scheduling and dispatching. It receives a request in the form of a call to its L<process()|Template::Service#process()> method and schedules the named template specified as an argument, and possibly several other templates (C<PRE_PROCESS>, etc) to be processed in order. It doesn't actually process the templates itself, but instead makes a L<process()|Template::Context#process()> call against a L<Template::Context> object. L<Template::Context> is the runtime engine for the Template Toolkit - the module that hangs everything together in the lower levels of the Template Toolkit and that one that does most of the real work, albeit by crafty delegation to various other friendly helper modules. Given a template name (or perhaps a reference to a scalar or file handle) the context process() method must load and compile, or fetch a cached copy of a previously compiled template, corresponding to that name. It does this by calling on a list of one or more L<Template::Provider> objects (the C<LOAD_TEMPLATES> posse) who themselves might get involved with a L<Template::Parser> to help turn source templates into executable Perl code (but more on that later). Thankfully, all of this complexity is hidden away behind a simple L<template()|Template::Context#template()> method. You call it passing a template name as an argument, and it returns a compiled template in the form of a L<Template::Document> object, or otherwise raises an exception. A L<Template::Document> is a thin object wrapper around a compiled template subroutine. The object implements a L<process()|Template::Document#process()> method which performs a little bit of housekeeping and then calls the template subroutine. The object also defines template metadata (defined in C<[% META ... %]> directives) and has a L<block()|Template::Document#block()> method which returns a hash of any additional C<[% BLOCK xxxx %]> definitions found in the template source. So the context fetches a compiled document via its own L<template()|Template::Context#template()> method and then gets ready to process it. It first updates the stash (the place where template variables get defined - more on that shortly) to set any template variable definitions specified as the second argument by reference to hash array. Then, it calls the document L<process()|Template::Document#process()> method, passing a reference to itself, the context object, as an argument. In doing this, it provides itself as an object against which template code can make callbacks to access runtime resources and Template Toolkit functionality. What we're trying to say here is this: not only does the L<Template::Context> object receive calls from the I<outside>, i.e. those originating in user code calling the process() method on a Template object, but it also receives calls from the I<inside>, i.e. those originating in template directives of the form C<[% PROCESS template %]>. Before we move on to that, here's a simple structure diagram showing the outer layers of the Template Toolkit heading inwards, with pseudo code annotations showing a typical invocation sequence. ,--------. | Caller | use Template; `--------' my $tt = Template->new( ... ); | $tt->process($template, \%vars); | Outside - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - T T | package Template; Inside V +----------+ sub process($template, \%vars) { | Template | $out = $self->SERVICE->process($template, $vars); +----------+ print $out or send it to $self->OUTPUT; | } | | package Template::Service; | | sub process($template, \%vars) { | try { +----------+ foreach $p in @self->PRE_PROCESS | Service | $self->CONTEXT->process($p, $vars); +----------+ | $self->CONTEXT->process($template, $vars); | | foreach $p @self->POST_PROCESS | $self->CONTEXT->process($p, $vars); | } | catch { | $self->CONTEXT->process($self->ERROR); | } | } | V package Template::Context; +----------+ | Context | sub process($template, \%vars) { +----------+ # fetch compiled template | $template = $self->template($template) | # update stash | $self->STASH->update($vars); | # process template | $template->process($self) | } V +----------+ package Template::Document; | Document | +----------+ sub process($context) { $output = &{ $self->BLOCK }($context); } =head1 Inside Looking Out To understand more about what's going on in these lower levels, we need to look at what a compiled template looks like. In fact, a compiled template is just a regular Perl sub-routine. Here's a very simple one. sub my_compiled_template { return "This is a compiled template.\n"; } You're unlikely to see a compiled template this simple unless you wrote it yourself but it is entirely valid. All a template subroutine is obliged to do is return some output (which may be an empty of course). If it can't for some reason, then it should raise an error via C<die()>. sub my_todo_template { die "This template not yet implemented\n"; } If it wants to get fancy, it can raise an error as a L<Template::Exception> object. An exception object is really just a convenient wrapper for the 'C<type>' and 'C<info>' fields. sub my_solilique_template { die (Template::Exception->new('yorrick', 'Fellow of infinite jest')); } Templates generally need to do a lot more than just generate static output or raise errors. They may want to inspect variable values, process another template, load a plugin, run a filter, and so on. Whenever a template subroutine is called, it gets passed a reference to a L<Template::Context> object. It is through this context object that template code can access the features of the Template Toolkit. We described earlier how the L<Template::Service> object calls on L<Template::Context> to handle a L<process()|Template::Context#process()> request from the I<outside>. We can make a similar request on a context to process a template, but from within the code of another template. This is a call from the I<inside>. sub my_process_template { my $context = shift; my $output = $context->process('header', { title => 'Hello World' }) . "\nsome content\n" . $context->process('footer'); } This is then roughly equivalent to a source template something like this: [% PROCESS header title = 'Hello World' %] some content [% PROCESS footer %] Template variables are stored in, and managed by a L<Template::Stash> object. This is a blessed hash array in which template variables are defined. The object wrapper provides L<get()|Template::Stash#get()> and L<set()|Template::Stash#set()> method which implement all the I<magical.variable.features> of the Template Toolkit. Each context object has its own stash, a reference to which can be returned by the appropriately named L<stash()|Template::Context#stash()> method. So to print the value of some template variable, or for example, to represent the following source template: <title>[% title %] we might have a subroutine definition something like this: sub { my $context = shift; my $stash = $context->stash(); return '' . $stash->get('title') . ''; } The stash L method hides the details of the underlying variable types, automatically calling code references, checking return values, and performing other such tricks. If 'C' happens to be bound to a subroutine then we can specify additional parameters as a list reference passed as the second argument to get(). [% title('The Cat Sat on the Mat') %] This translates to the stash call: $stash->get([ 'title', ['The Cat Sat on the Mat'] ]); Dotted compound variables can be requested by passing a single list reference to the C<get()> method in place of the variable name. Each pair of elements in the list should correspond to the variable name and reference to a list of arguments for each dot-delimited element of the variable. [% foo(1, 2).bar(3, 4).baz(5) %] is thus equivalent to $stash->get([ foo => [1,2], bar => [3,4], baz => [5] ]); If there aren't any arguments for an element, you can specify an empty, zero or null argument list. [% foo.bar %] $stash->get([ 'foo', 0, 'bar', 0 ]); The L<set()|Template::Stash#set()> method works in a similar way. It takes a variable name and a variable value which should be assigned to it. [% x = 10 %] $stash->set('x', 10); [% x.y = 10 %] $stash->set([ 'x', 0, 'y', 0 ], 10); So the stash gives us access to template variables and the context provides the higher level functionality. Alongside the L<process()|Template::Context#process()> method lies the L<include()|Template::Context#include()> method. Just as with the C<PROCESS> / C<INCLUDE> directives, the key difference is in variable localisation. Before processing a template, the C<process()> method simply updates the stash to set any new variable definitions, overwriting any existing values. In contrast, the C<include()> method creates a copy of the existing stash, in a process known as I<cloning> the stash, and then uses that as a temporary variable store. Any previously existing variables are still defined, but any changes made to variables, including setting the new variable values passed aas arguments will affect only the local copy of the stash (although note that it's only a shallow copy, so it's not foolproof). When the template has been processed, the C<include()> method restores the previous variable state by I<decloning> the stash. The context also provides an L<insert()|Template::Context#insert()> method to implement the C<INSERT> directive, but no C<wrapper()> method. This functionality can be implemented by rewriting the Perl code and calling C<include()>. [% WRAPPER foo -%] blah blah [% x %] [%- END %] $context->include('foo', { content => 'blah blah ' . $stash->get('x'), }); Other than the template processing methods C<process()>, C<include()> and C<insert()>, the context defines methods for fetching plugin objects, L<plugin()|Template::Context#plugin()>, and filters, L<filter()|Template::Context#filter()>. # TT USE directive [% USE foo = Bar(10) %] # equivalent Perl $stash->set('foo', $context->plugin('Bar', [10])); # TT FILTER block [% FILTER bar(20) %] blah blah blah [% END %] # equivalent Perl my $filter = $context->filter('bar', [20]); &$filter('blah blah blah'); Pretty much everything else you might want to do in a template can be done in Perl code. Things like C<IF>, C<UNLESS>, C<FOREACH> and so on all have direct counterparts in Perl. # TT IF directive [% IF msg %] Message: [% msg %] [% END %]; # equivalent Perl if ($stash->get('msg')) { $output .= 'Message: '; $output .= $stash->get('msg'); } The best way to get a better understanding of what's going on underneath the hood is to set the C<$Template::Parser::DEBUG> flag to a true value and start processing templates. This will cause the parser to print the generated Perl code for each template it compiles to C<STDERR>. You'll probably also want to set the C<$Template::Directive::PRETTY> option to have the Perl pretty-printed for human consumption. use Template; use Template::Parser; use Template::Directive; $Template::Parser::DEBUG = 1; $Template::Directive::PRETTY = 1; my $template = Template->new(); $template->process(\*DATA, { cat => 'dog', mat => 'log' }); __DATA__ The [% cat %] sat on the [% mat %] The output sent to C<STDOUT> remains as you would expect: The dog sat on the log The output sent to C<STDERR> would look something like this: compiled main template document block: sub { my $context = shift || die "template sub called without context\n"; my $stash = $context->stash; my $output = ''; my $error; eval { BLOCK: { $output .= "The "; $output .= $stash->get('cat'); $output .= " sat on the "; $output .= $stash->get('mat'); $output .= "\n"; } }; if ($@) { $error = $context->catch($@, \$output); die $error unless $error->type eq 'return'; } return $output; } =head1 Hacking on the Template Toolkit Please feel free to hack on the Template Toolkit. If you find a bug that needs fixing, if you have an idea for something that's missing, or you feel inclined to tackle something on the TODO list, then by all means go ahead and do it! If you're contemplating something non-trivial then you'll probably want to bring it up on the mailing list first to get an idea about the current state of play, find out if anyone's already working on it, and so on. The source code repository for the Template Toolkit is hosted at Github. https://github.com/abw/Template2 Clone the repository, make your changes, commit them, then send a pull request. Once you've made your changes, please remember to update the test suite by adding extra tests to one of the existing test scripts in the C<t> sub-directory, or by adding a new test script of your own. And of course, run C<make test> to ensure that all the tests pass with your new code. Don't forget that any files you do add will need to be added to the MANIFEST. Running C<make manifest> will do this for you, but you need to make sure you haven't got any other temporary files lying around that might also get added to it. Documentation is often something that gets overlooked but it's just as important as the code. If you're adding a new module, a plugin module, for example, then it's OK to include the POD documentation in with the module, but I<please> write it all in one piece at the end of the file, I<after> the code (just look at any other C<Template::*> module for an example). It's a religious issue, I know, but I have a strong distaste for POD documentation interspersed throughout the code. In my not-so-humble opinion, it makes both the code and the documentation harder to read (same kinda problem as embedding Perl in HTML). Then add a line to the Changes file giving a very brief description of what you've done. There's no need to go into detail here (save that for the commit message, comments in code or docuemtation where appropriate). Please also make sure you add your name to the lib/Template/Manual/Credits.pod file (if it isn't already there). Then commit your changes and send a pull request. =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ]OX��X�� ��VMethods.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::VMethods # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::VMethods - Virtual Methods =head1 Root Virtual Methods These virtual methods can be applied to any variable type (scalars, hash arrays, and lists). =head2 inc Increments the value of a variable and returns the new value. [% counter = 10; counter.inc; # 11 counter # 11 (variable is modified in place) %] =head2 dec Decrements the value of a variable and returns the new value. [% counter = 10; counter.dec; # 9 counter # 9 (variable is modified in place) %] =head1 Scalar Virtual Methods =head2 chunk(size) Splits the value into a list of chunks of a certain size. [% ccard_no = "1234567824683579"; ccard_no.chunk(4).join %] Output: 1234 5678 2468 3579 If the size is specified as a negative number then the text will be chunked from right-to-left. This gives the correct grouping for numbers, for example. [% number = 1234567; number.chunk(-3).join(',') %] Output: 1,234,567 =head2 collapse Returns the text with any leading and trailing whitespace removed and any internal sequences of whitespace converted to a single space [% text = " The bird\n is the word" %] [% text.collapse %] # The bird is the word =head2 defined Returns true if the value is defined. [% user = get_user(uid) IF uid.defined %] =head2 dquote Returns the text with any double quote characters escaped with a backslash prefix. Any newline characters in the text will be replaced with "\n". [% quote = 'He said "Oh really?"' %] [% quote.dquote %] # He said \"Oh really?\" =head2 hash Return the value as a hash reference containing a single entry with the key C<value> indicating the original scalar value. As with the C<list> virtual method, this is generally used to help massage data into different formats. =head2 html Returns the text with any HTML special characters escaped to their entity equivalents: C<< & >> to C<< & >>, C<< < >> to C<< < >>, C<< > >> to C<< > >>, C<< " >> to C<< " >>, and C<< ' >> to C<< ' >>. [% text = '<script>alert("XSS")</script>' %] [% text.html %] # <script>alert("XSS")</script> =head2 item Returns the value itself. This is generally not useful by itself but provides consistency with the hash and list C<item> methods. [% foo = 'bar' %] [% foo.item %] # bar =head2 lcfirst Returns the text with the first letter converted to lower case. [% word = 'BIRD' %] [% word.lcfirst %] # bIRD =head2 length Returns the length of the string representation of the item: [% IF password.length < 8 %] Password too short, dumbass! [% END %] =head2 empty Returns true if the string is empty: [% IF details.empty %] No details specified [% END %] =head2 list Return the value as a single element list. This can be useful if you have a variable which may contain a single item or a list and you want to treat them equally. The C<list> method can be called against a list reference and will simply return the original reference, effectively a no-op. [% thing.list.size %] # thing can be a scalar or a list =head2 lower Returns the text in lower case. [% word = 'BIRD' %] [% word.lower %] # bird =head2 match(pattern, global) Performs a regular expression match on the string using the pattern passed as an argument. If the pattern matches the string then the method returns a reference to a list of any strings captured within parenthesis in the pattern. [% name = 'Larry Wall' %] [% matches = name.match('(\w+) (\w+)') %] [% matches.1 %], [% matches.0 %] # Wall, Larry If the pattern does not match then the method returns false, rather than returning an empty list which Perl and the Template Toolkit both consider to be a true value. This allows you to write expression like this. [% "We're not worthy!" IF name.match('Larry Wall') %] [% IF (matches = name.match('(\w+) (\w+)')) %] pattern matches: [% matches.join(', ') %] [% ELSE %] pattern does not match [% END %] Any regex modifiers, like C</s>, should be added in the regex using the C<(?s)> syntax. For example, to modify the regex to disregard whitespace (the C</x> switch), use: [% re = '(?x) (\w+) [ ] (\w+) '; matches = name.match(re); %] To perform a global search to match the pattern as many times as it appears in the source string, provide a true value for the C<global> argument following the pattern. [% text = 'bandanna'; text.match('an+', 1).join(', ') # an, ann %] =head2 repeat(n) Repeat the string a specified number of times. [% name = 'foo' %] [% name.repeat(3) %] # foofoofoo =head2 replace(search, replace) Outputs the string with all instances of the first argument (specified as a Perl regular expression) with the second. [% name = 'foo, bar & baz' %] [% name.replace('\W+', '_') %] # foo_bar_baz You can use C<$1>, C<$2>, etc., to reference captured parts (in parentheses) in the regular expression. Just be careful to I<single> quote the replacement string. If you use I<double> quotes then TT will try and interpolate the variables before passing the string to the C<replace> vmethod. [% name = 'FooBarBaz' %] [% name.replace('([A-Z])', ' $1') %] # Foo Bar Baz =head2 remove(pattern) Outputs the string with all instances of the pattern (specified as a Perl regular expression) removed. [% name = 'foo, bar & baz' %] [% name.remove('\W+') %] # foobarbaz =head2 search(pattern) Performs a similar function to L<match> but simply returns true if the string matches the regular expression pattern passed as an argument. [% name = 'foo bar baz' %] [% name.search('bar') ? 'bar' : 'no bar' %] # bar This virtual method is now deprecated in favour of L<match>. Move along now, there's nothing more to see here. =head2 size Always returns 1 for scalar values. This method is provided for consistency with the hash and list size methods. =head2 split(pattern) Calls Perl's C<split()> function to split a string into a list of strings. [% FOREACH dir IN mypath.split(':') %] [% dir %] [% END %] =head2 substr(offset, length, replacement) Returns a substring starting at C<offset>, for C<length> characters. [% str 'foo bar baz wiz waz woz') %] [% str.substr(4, 3) %] # bar If C<length> is not specified then it returns everything from the C<offset> to the end of the string. [% str.substr(12) %] # wiz waz woz If both C<length> and C<replacement> are specified, then the method replaces everything from C<offset> for C<length> characters with C<$replacement>. The substring removed from the string is then returned. [% str.substr(0, 11, 'FOO') %] # foo bar baz [% str %] # FOO wiz waz woz =head2 squote Returns the text with any single quote characters escaped with a backslash prefix. [% tim = "Tim O'Reilly" %] [% tim.squote %] # Tim O\'Reilly =head2 trim Returns the text with any leading and trailing whitespace removed. [% text = ' hello world ' %] [% text.trim %] # hello world =head2 ucfirst Returns the text with the first letter converted to upper case. [% word = 'bird' %] [% word.ucfirst %] # Bird =head2 upper Returns the text in upper case. [% word = 'bird' %] [% word.upper %] # BIRD =head2 xml Same as C<html> but escapes single quotes to C<< ' >> (the XML named entity) instead of C<< ' >> (the HTML numeric reference). [% text = "Matt's <tag>" %] [% text.xml %] # Matt's <tag> =head1 Hash Virtual Methods =head2 keys Returns a list of keys in the hash. They are not returned in any particular order, but the order is the same as for the corresponding values method. [% FOREACH key IN hash.keys %] * [% key %] [% END %] If you want the keys in sorted order, use the list C<sort> method. [% FOREACH key IN hash.keys.sort %] * [% key %] [% END %] Having got the keys in sorted order, you can then use variable interpolation to fetch the value. This is shown in the following example by the use of C<$key> to fetch the item from C<hash> whose key is stored in the C<key> variable. [% FOREACH key IN hash.keys.sort %] * [% key %] = [% hash.$key %] [% END %] Alternately, you can use the C<pairs> method to get a list of key/value pairs in sorted order. =head2 values Returns a list of the values in the hash. As with the C<keys> method, they are not returned in any particular order, although it is the same order that the keys are returned in. [% hash.values.join(', ') %] =head2 items Returns a list of both the keys and the values expanded into a single list. [% hash = { a = 10 b = 20 }; hash.items.join(', ') # a, 10, b, 20 %] =head2 each This method currently returns the same thing as the C<items> method. However, please note that this method will change in the next major version of the Template Toolkit (v3) to return the same thing as the C<pairs> method. This will be done in an effort to make these virtual method more consistent with each other and how Perl works. In anticipation of this, we recommend that you stop using C<hash.each> and instead use C<hash.items>. =head2 pairs This method returns a list of key/value pairs. They are returned in sorted order according to the keys. [% FOREACH pair IN product.pairs %] * [% pair.key %] is [% pair.value %] [% END %] =head2 list Returns the contents of the hash in list form. An argument can be passed to indicate the desired items required in the list: C<keys> to return a list of the keys (same as C<hash.keys>), C<values> to return a list of the values (same as C<hash.values>), C<each> to return as list of key and values (same as C<hash.each>), or C<pairs> to return a list of key/value pairs (same as C<hash.pairs>). [% keys = hash.list('keys') %] [% values = hash.list('values') %] [% items = hash.list('each') %] [% pairs = hash.list('pairs') %] When called without an argument it currently returns the same thing as the C<pairs> method. However, please note that this method will change in the next major version of the Template Toolkit (v3) to return a reference to a list containing the single hash reference (as per the scalar list method). In anticipation of this, we recommend that you stop using C<hash.list> and instead use C<hash.pairs>. =head2 sort, nsort Return a list of the keys, sorted alphabetically (C<sort>) or numerically (C<nsort>) according to the corresponding values in the hash. [% FOREACH n IN phones.sort %] [% phones.$n %] is [% n %], [% END %] =head2 import The C<import> method can be called on a hash array to import the contents of another hash array. [% hash1 = { foo = 'Foo' bar = 'Bar' } hash2 = { wiz = 'Wiz' woz = 'Woz' } %] [% hash1.import(hash2) %] [% hash1.wiz %] # Wiz You can also call the C<import()> method by itself to import a hash array into the current namespace hash. [% user = { id => 'lwall', name => 'Larry Wall' } %] [% import(user) %] [% id %]: [% name %] # lwall: Larry Wall =head2 defined, exists Returns a true or false value if an item in the hash denoted by the key passed as an argument is defined or exists, respectively. [% hash.defined('somekey') ? 'yes' : 'no' %] [% hash.exists('somekey') ? 'yes' : 'no' %] When called without any argument, C<hash.defined> returns true if the hash itself is defined (e.g. the same effect as C<scalar.defined>). =head2 delete Delete one or more items from the hash. [% hash.delete('foo', 'bar') %] =head2 size Returns the number of key/value pairs in the hash. =head2 empty Returns true if the hash is empty: [% IF config.empty %] No configuration available [% END %] =head2 hash Returns the hash itself. This is provided for consistency with the scalar and list C<hash> methods, and is a no-op. [% hash.hash %] # same as hash =head2 item Returns an item from the hash using a key passed as an argument. [% hash.item('foo') %] # same as hash.foo =head1 List Virtual Methods =head2 first, last Returns the first/last item in the list. The item is not removed from the list. [% results.first %] to [% results.last %] If either is given a numeric argument C<n>, they return the first or last C<n> elements: The first 5 results are [% results.first(5).join(", ") %]. =head2 size, max Returns the size of a list (number of elements) and the maximum index number (size - 1), respectively. [% results.size %] search results matched your query =head2 empty Returns true if the list is empty: [% IF results.empty %] No results found [% END %] =head2 defined Returns a true or false value if the item in the list denoted by the argument is defined. [% list.defined(3) ? 'yes' : 'no' %] When called without any argument, C<list.defined> returns true if the list itself is defined (e.g. the same effect as C<scalar.defined>). =head2 reverse Returns the items of the list in reverse order. [% FOREACH s IN scores.reverse %] ... [% END %] =head2 join Joins the items in the list into a single string, using Perl's C<join()> function. [% items.join(', ') %] =head2 grep Returns a list of the items in the list that match a regular expression pattern. [% FOREACH directory.files.grep('\.txt$') %] ... [% END %] If the pattern is C<undef> or an empty string, no items are returned. =head2 sort, nsort Returns the items in alpha (C<sort>) or numerical (C<nsort>) order. [% library = books.sort %] An argument can be provided to specify a search key. Where an item in the list is a hash reference, the search key will be used to retrieve a value from the hash which will then be used as the comparison value. Where an item is an object which implements a method of that name, the method will be called to return a comparison value. [% library = books.sort('author') %] In the example, the C<books> list can contains hash references with an C<author> key or objects with an C<author> method. You can also specify multiple sort keys. [% library = books.sort('author', 'title') %] In this case the books will be sorted primarily by author. If two or more books have authors with the same name then they will be sorted by title. =head2 unshift(item), push(item) The C<push()> method adds an item or items to the end of list. [% mylist.push(foo) %] [% mylist.push(foo, bar) %] The C<unshift()> method adds an item or items to the start of a list. [% mylist.unshift(foo) %] [% mylist.push(foo, bar) %] =head2 shift, pop Removes the first/last item from the list and returns it. [% first = mylist.shift %] [% last = mylist.pop %] =head2 unique Returns a list of the unique elements in a list, in the same order as in the list itself. [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %] [% numbers = mylist.unique %] While this can be explicitly sorted, it is not required that the list be sorted before the unique elements are pulled out (unlike the Unix command line utility). [% numbers = mylist.unique.sort %] =head2 import Appends the contents of one or more other lists to the end of the current list. [% one = [ 1 2 3 ]; two = [ 4 5 6 ]; three = [ 7 8 9 ]; one.import(two, three); one.join(', '); # 1, 2, 3, 4, 5, 6, 7, 8, 9 %] Import also allows chaining. The below syntax is equivalent. [% one = [ 1 2 3 ]; two = [ 4 5 6 ]; three = [ 7 8 9 ]; one.import(two, three).join(', '); # 1, 2, 3, 4, 5, 6, 7, 8, 9 # or: one.import(two).import(three).join(', '); # 1, 2, 3, 4, 5, 6, 7, 8, 9 %] =head2 merge Returns a list composed of zero or more other lists: [% list_one = [ 1 2 3 ]; list_two = [ 4 5 6 ]; list_three = [ 7 8 9 ]; list_four = list_one.merge(list_two, list_three); %] The original lists are not modified. =head2 slice(from, to) Returns a slice of items in the list between the bounds passed as arguments. If the second argument, C<to>, isn't specified, then it defaults to the last item in the list. The original list is not modified. [% first_three = list.slice(0,2) %] [% last_three = list.slice(-3, -1) %] =head2 splice(offset, length, list) Behaves just like Perl's C<splice()> function allowing you to selectively remove and/or replace elements in a list. It removes C<length> items from the list, starting at C<offset> and replaces them with the items in C<list>. [% play_game = [ 'play', 'scrabble' ]; ping_pong = [ 'ping', 'pong' ]; redundant = play_game.splice(1, 1, ping_pong); redundant.join; # scrabble play_game.join; # play ping pong %] The method returns a list of the items removed by the splice. You can use the C<CALL> directive to ignore the output if you're not planning to do anything with it. [% CALL play_game.splice(1, 1, ping_pong) %] As well as providing a reference to a list of replacement values, you can pass in a list of items. [% CALL list.splice(-1, 0, 'foo', 'bar') %] Be careful about passing just one item in as a replacement value. If it is a reference to a list then the contents of the list will be used. If it's not a list, then it will be treated as a single value. You can use square brackets around a single item if you need to be explicit: [% # push a single item, an_item CALL list.splice(-1, 0, an_item); # push the items from another_list CALL list.splice(-1, 0, another_list); # push a reference to another_list CALL list.splice(-1, 0, [ another_list ]); %] =head2 hash Returns a reference to a hash array comprised of the elements in the list. The even-numbered elements (0, 2, 4, etc) become the keys and the odd-numbered elements (1, 3, 5, etc) the values. [% list = ['pi', 3.14, 'e', 2.718] %] [% hash = list.hash %] [% hash.pi %] # 3.14 [% hash.e %] # 2.718 If a numerical argument is provided then the hash returned will have keys generated for each item starting at the number specified. [% list = ['beer', 'peanuts'] %] [% hash = list.hash(1) %] [% hash.1 %] # beer [% hash.2 %] # peanuts =head2 item Returns an item from the list using an index passed as an argument. [% list.item(0) %] # same as list.0 =head2 list Returns the list itself. This is provided for consistency with the scalar C<list> method (which wraps a scalar in a list) and is a no-op on list references. [% list.list %] # same as list =head1 Automagic Promotion of Scalar to List for Virtual Methods In addition to the scalar virtual methods listed in the previous section, you can also call any list virtual method against a scalar. The item will be automagically promoted to a single element list and the appropriate list virtual method will be called. One particular benefit of this comes when calling subroutines or object methods that return a list of items, rather than the preferred reference to a list of items. In this case, the Template Toolkit automatically folds the items returned into a list. The upshot is that you can continue to use existing Perl modules or code that returns lists of items, without having to refactor it just to keep the Template Toolkit happy (by returning references to list). C<Class::DBI> module is just one example of a particularly useful module which returns values this way. If only a single item is returned from a subroutine then the Template Toolkit assumes it meant to return a single item (rather than a list of 1 item) and leaves it well alone, returning the single value as it is. If you're executing a database query, for example, you might get 1 item returned, or perhaps many items which are then folded into a list. The C<FOREACH> directive will happily accept either a list or a single item which it will treat as a list. So it's safe to write directives like this, where we assume that the C<something> variable is bound to a subroutine which may return one or more items: [% FOREACH item IN something %] ... [% END %] The automagic promotion of scalars to single item lists means that you can also use list virtual methods safely, even if you only get one item returned. For example: [% something.first %] [% something.join %] [% something.reverse.join(', ') %] Note that this is very much a last-ditch behaviour. If the single item return is an object with a C<first> method, for example, then that will be called, as expected, in preference to the list virtual method. =head1 Defining Custom Virtual Methods You can define your own virtual methods for scalars, lists and hash arrays. The L<Template::Stash> package variables C<$SCALAR_OPS>, C<$LIST_OPS> and C<$HASH_OPS> are references to hash arrays that define these virtual methods. C<HASH_OPS> and C<LIST_OPS> methods are subroutines that accept a hash/list reference as the first item. C<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 ]; }; Example template: [% primes = [ 2, 3, 5, 7, 9 ] %] [% primes.odd.join(', ') %] # 3, 5, 7, 9 TODO: document the define_vmethod() method which makes this even easier =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ]XC(��(�� ��Plugins.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::Plugins # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Plugins - Standard plugins =head1 TEMPLATE TOOLKIT PLUGINS The following plugin modules are distributed with the Template Toolkit. Some of the plugins interface to external modules (detailed below) which should be downloaded from any CPAN site and installed before using the plugin. =head2 Assert New in 2.20! The L<Assert|Template::Plugin::Assert> plugin adds an C<assert> virtual method that you can use to catch undefined values. For example, consider this dotop: [% user.name %] If C<user.name> is an undefined value then TT will silently ignore the fact and print nothing. If you C<USE> the C<assert> plugin then you can add the C<assert> vmethod between the C<user> and C<name> elements, like so: [% user.assert.name %] Now, if C<user.name> is an undefined value, an exception will be thrown: assert error - undefined value for name =head2 CGI The L<CGI|Template::Plugin::CGI> plugin is a wrapper around Lincoln Stein's CGI.pm module. The plugin is distributed with the Template Toolkit (see L<Template::Plugin::CGI>) and the L<CGI> module itself is distributed with recent versions Perl, or is available from CPAN. [% USE CGI %] [% CGI.param('param_name') %] [% CGI.start_form %] [% CGI.popup_menu( Name => 'color', Values => [ 'Green', 'Brown' ] ) %] [% CGI.end_form %] =head2 Datafile Provides an interface to data stored in a plain text file in a simple delimited format. The first line in the file specifies field names which should be delimiter by any non-word character sequence. Subsequent lines define data using the same delimiter as in the first line. Blank lines and comments (lines starting '#') are ignored. See L<Template::Plugin::Datafile> for further details. /tmp/mydata: # define names for each field id : email : name : tel # here's the data fred : fred@here.com : Fred Smith : 555-1234 bill : bill@here.com : Bill White : 555-5678 example: [% USE userlist = datafile('/tmp/mydata') %] [% FOREACH user = userlist %] [% user.name %] ([% user.id %]) [% END %] =head2 Date The L<Date|Template::Plugin::Date> plugin provides an easy way to generate formatted time and date strings by delegating to the L<POSIX> C<strftime()> routine. See L<Template::Plugin::Date> and L<POSIX> for further details. [% USE date %] [% date.format %] # current time/date File last modified: [% date.format(template.modtime) %] =head2 Directory The L<Directory|Template::Plugin::Directory> plugin provides a simple interface to a directory and the files within it. See L<Template::Plugin::Directory> for further details. [% USE dir = Directory('/tmp') %] [% FOREACH file = dir.files %] # all the plain files in the directory [% END %] [% FOREACH file = dir.dirs %] # all the sub-directories [% END %] =head2 DBI The C<DBI> plugin is no longer distributed as part of the Template Toolkit (as of version 2.15). It is now available as a separate L<Template::DBI> distribution from CPAN. =head2 Dumper The L<Dumper|Template::Plugin::Dumper> plugin provides an interface to the Data::Dumper module. See L<Template::Plugin::Dumper> and L<Data::Dumper> for further details. [% USE dumper(indent=0, pad="<br>") %] [% dumper.dump(myvar, yourvar) %] =head2 File The L<File|Template::Plugin::File> plugin provides a general abstraction for files and can be used to fetch information about specific files within a filesystem. See L<Template::Plugin::File> for further details. [% USE File('/tmp/foo.html') %] [% File.name %] # foo.html [% File.dir %] # /tmp [% File.mtime %] # modification time =head2 Filter This module implements a base class plugin which can be subclassed to easily create your own modules that define and install new filters. package MyOrg::Template::Plugin::MyFilter; use Template::Plugin::Filter; use base qw( Template::Plugin::Filter ); sub filter { my ($self, $text) = @_; # ...mungify $text... return $text; } Example of use: # now load it... [% USE MyFilter %] # ...and use the returned object as a filter [% FILTER $MyFilter %] ... [% END %] See L<Template::Plugin::Filter> for further details. =head2 Format The L<Format|Template::Plugin::Format> plugin provides a simple way to format text according to a C<printf()>-like format. See L<Template::Plugin::Format> for further details. [% USE bold = format('<b>%s</b>') %] [% bold('Hello') %] =head2 GD The C<GD> plugins are no longer part of the core Template Toolkit distribution. They are now available from CPAN in a separate L<Template::GD> distribution. =head2 HTML The L<HTML|Template::Plugin::HTML> plugin is very basic, implementing a few useful methods for generating HTML. It is likely to be extended in the future or integrated with a larger project to generate HTML elements in a generic way. [% USE HTML %] [% HTML.escape("if (a < b && c > d) ..." %] [% HTML.attributes(border => 1, cellpadding => 2) %] [% HTML.element(table => { border => 1, cellpadding => 2 }) %] See L<Template::Plugin::HTML> for further details. =head2 Iterator The L<Iterator|Template::Plugin::Iterator> plugin provides a way to create a L<Template::Iterator> object to iterate over a data set. An iterator is created automatically by the C<FOREACH> directive and is aliased to the C<loop> variable. This plugin allows an iterator to be explicitly created with a given name, or the default plugin name, C<iterator>. See L<Template::Plugin::Iterator> for further details. [% USE iterator(list, args) %] [% FOREACH item = iterator %] [% '<ul>' IF iterator.first %] <li>[% item %] [% '</ul>' IF iterator.last %] [% END %] =head2 List The L<List|Template::Plugin::List> plugin provides an object-oriented interface to lists. See L<Template::Plugin::List> for further details. [% USE list = List(1, 2, 3, 4, 5) %] [% list.size %] # 5 [% list.item(0) %] # 1 [% list.text %] # 1, 2, 3, 4, 5 [% CALL list.push(6) %] [% list.size %] # 6 =head2 Math The L<Math|Template::Plugin::Math> plugin provides numerous mathematical functions for use within templates. It wraps Perl core math functions (C<abs>, C<cos>, C<exp>, C<hex>, C<int>, C<log>, C<oct>, C<rand>, C<sin>, C<sqrt>, etc.) and also makes additional trigonometric functions available if L<Math::Trig> is installed. See L<Template::Plugin::Math> for further details. [% USE Math %] [% Math.sqrt(9) %] # 3 [% Math.abs(-42) %] # 42 [% Math.hex('ff') %] # 255 =head2 Pod This plugin provides an interface to the L<Pod::POM|Pod::POM> module which parses POD documents into an internal object model which can then be traversed and presented through the Template Toolkit. [% USE Pod(podfile) %] [% FOREACH head1 = Pod.head1; FOREACH head2 = head1/head2; ... END; END %] =head2 Scalar The Template Toolkit calls user-defined subroutines and object methods using Perl's array context by default. # TT2 calls object methods in array context by default [% object.method %] This plugin module provides a way for you to call subroutines and methods in scalar context. [% USE scalar %] # force it to use scalar context [% object.scalar.method %] # also works with subroutine references [% scalar.my_sub_ref %] =head2 String The L<String|Template::Plugin::String> plugin implements an object-oriented interface for manipulating strings. See L<Template::Plugin::String> for further details. [% USE String 'Hello' %] [% String.append(' World') %] [% msg = String.new('Another string') %] [% msg.replace('string', 'text') %] The string "[% msg %]" is [% msg.length %] characters long. =head2 Table The L<Table|Template::Plugin::Table> plugin allows you to format a list of data items into a virtual table by specifying a fixed number of rows or columns, with an optional overlap. See L<Template::Plugin::Table> for further details. [% USE table(list, rows=10, overlap=1) %] [% FOREACH item = table.col(3) %] [% item %] [% END %] =head2 URL The L<URL|Template::Plugin::URL> plugin provides a simple way of constructing URLs from a base part and a variable set of parameters. See L<Template::Plugin::URL> for further details. [% USE mycgi = url('/cgi-bin/bar.pl', debug=1) %] [% mycgi %] # ==> /cgi/bin/bar.pl?debug=1 [% mycgi(mode='submit') %] # ==> /cgi/bin/bar.pl?mode=submit&debug=1 =head2 View The L<View|Template::Plugin::View> plugin creates L<Template::View> objects. Views provide a mechanism for applying template-based "skins" to data objects, using a prefix and/or suffix to map method calls to templates. Views are an experimental feature. See L<Template::Plugin::View> and L<Template::View> for further details. [% USE view(prefix = 'my/') %] [% view.header(title = 'Hello') %] # processes 'my/header' =head2 Wrap The L<Wrap|Template::Plugin::Wrap> plugin uses the L<Text::Wrap> module to provide simple paragraph formatting. See L<Template::Plugin::Wrap> and L<Text::Wrap> for further details. [% USE wrap %] [% wrap(mytext, 40, '* ', ' ') %] # use wrap sub [% mytext FILTER wrap(40) -%] # or wrap FILTER The C<Text::Wrap> module is available from CPAN: http://www.cpan.org/modules/by-module/Text/ =head2 XML The C<XML::DOM>, C<XML::RSS>, C<XML::Simple> and C<XML::XPath> plugins are no longer distributed with the Template Toolkit as of version 2.15 They are now available in a separate L<Template::XML> distribution. =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ]zSiN��N�� ��Credits.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::Credits # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =encoding utf8 =head1 NAME Template::Manual::Credits - Author and contributor credits =head1 HISTORY The Template Toolkit began its life as the C<Text::MetaText> module, originally released to CPAN around 1996. This itself was the public manifestation of an earlier template processing system I developed while working at Peritas (now Knowledge Pool - http://www.knowledgepool.com/) C<Text::MetaText> was the prototype - the one we always planned to throw away. It did the job well, showing us what worked and what didn't, what was good and what was bad, and gave us some ideas about what could be done better, given the chance to start again from scratch. Some time late in 1998 I threw away the prototype and started work on the Template Toolkit. By then I was working at Canon Research Centre Europe Ltd. (CRE), involved in a general research programme related to web publishing and dynamic content generation. The first alpha release was in June 1999, followed by numerous more alpha and beta releases culminating in 1.00 being released on 2nd December 1999. A month or so later, work had begun on version 2.00. The plan was to get the template language relatively stable in version 1.00 and not worry too much about performance or other internal matters. Then, version 2.00 would follow to improve performance, clean up the architecture and fix anything that, with the benefit of hindsight, we thought could be improved. As it happens, me starting work on version 2.00 coincided with Doug Steinwand sending me his parser variant which compiled templates to Perl code, giving a major performance boost. As well as the speedups, there are a whole host of significant new features in version 2.00, and a greatly improved internal architecture. Apart from a few minor "fixups" the template directives and language have remained the same as in version 1.00 Version 2.00 was available in beta release form in July 2000, just in time for the 4th Perl Conference where version 1.00 was awarded "Best New Perl Module". After another extended beta release period, version 2.00 was released on 1st December 2000. Version 3 has been in development ever since. =head1 AUTHOR Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/> =head1 COPYRIGHT Copyright (C) 1996-2020 Andy Wardley. All Rights Reserved. The Template Toolkit is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 CONTRIBUTORS Many people have contributed ideas, inspiration, fixes and features to the Template Toolkit. Their efforts continue to be very much appreciated. Please let me know if you think anyone is missing from this list. If you submit a patch/pull request then please make sure you add your own name to this list and include it in the changes. Adam Kennedy, ahollandECS, Alexey A. Kiritchun, Amiri Barksdale, Andreas Koenig, Andy Wardley, Autrijus Tang, Axel Gerstmair, Barrie Slaymaker, Ben Tilly, Breno G. de Oliveira, Briac PilprE<eacute>, Brian Fraser, Brian Wightman, Bryce Harrington, Chris Dean, Chris Winters, Christian, chromatic, Colin Johnson, Colin Keith, Craig Barratt, Darren Chamberlain, Dave Cash, Dave Cross, Dave Hodgkinson, Dave Howorth, Dave Jacoby, David Steinbrunner, Denis F. Latypoff, Dennis Clark, Doug, Drew Taylor, Dylan, E. Choroba, eadjei, Eric Cholet, Francois Desarmenien, François Andriot, fREW Schmidt, gordon-fish, Guido Flohr, Hans von Lengerke, Harald Joerg, Horst Dumcke, Ivan Krylov, Ivan Kurmanov, Jacques Germishuys, Jason Lewis, Jay Hannah, Jens Rehsack, Jess Robinson, Jim Vaughan, John Lightsey, John Napiorkowski, Jon Jensen, Jonas Liljegren, Jonathon Padfield, José Joaquín Atria, Jose Luis Martinez, Josh Rosenbaum, Kenny Gatdula, Kent Fredric, Kevin M. Goess, Koenig, Leon Brocard, Leslie Michael Orchard, Lubomir, Lyle Brooks, Marc Remy, Mark Fowler, Martin, Matthew Somerville, Michael Fowler, Michael Stevens, Mike Schilli, Mikhail Klyuchnikov from Positive Technologies, nataraj, Neil Bowers, Nick Hibma, Nicolas R, Nik Clayton, Norbert Buchmüller, Paul Orrock, Paul Seamons, Paul Sharpe, Perrin Harkins, Philippe Bruhat (BooK), Piers Cawley, Portman, Rafael Kitover, Randal L. Schwartz, Ricardo Signes, Richard Tietjen, Robin Berjon, Rod Taylor, Schaffner, sdeseille, Sean McAfee, Sean Zellmer, Simon, Simon Dawson, Simon Matthews, Simon Napiorkowski, Slaven Rezic, Smylers, Stas Bekman, Stathy G. Touloumis, stefano-b, Steinwand, Steve Peters, Swen, Thierry-Michel Barral, Thuemmler, Timmy Chan, Todd Rinaldo, Tom Delmas, Tony Bowden, Tosh Cooey, Ville SkyttE<auml>, Vivek Khera, Wilcox, William Hardison, Yanick Champoux, Yuri Pimenov. =cut # Local Variables: # mode: perl # perl-indent-level: 4 # indent-tabs-mode: nil # End: # # vim: expandtab shiftwidth=4: PK�����! ]@bJ��J����Directives.podnu�6$��������#============================================================= -*-perl-*- # # Template::Manual::Directives # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Directives - Template directives =head1 Accessing and Updating Template Variables =head2 GET The C<GET> directive retrieves and outputs the value of the named variable. [% GET foo %] The C<GET> keyword is optional. A variable can be specified in a directive tag by itself. [% foo %] The variable can have an unlimited number of elements, each separated by a dot. Each element can have arguments specified within parentheses. [% foo %] [% bar.baz %] [% biz.baz(10) %] ...etc... See L<Template::Manual::Variables> for a full discussion on template variables. You can also specify expressions using the logical (C<and>, C<or>, C<not>, C<?>, C<:>) and mathematic operators (C<+>, C<->, C<*>, C</>, C<%>, C<mod>, C<div>). [% template.title or default.title %] [% score * 100 %] [% order.nitems ? checkout(order.total) : 'no items' %] The C<div> operator returns the integer result of division. Both C<%> and C<mod> return the modulus (i.e. remainder) of division. [% 15 / 6 %] # 2.5 [% 15 div 6 %] # 2 [% 15 mod 6 %] # 3 =head2 CALL The C<CALL> directive is similar to C<GET> in evaluating the variable named, but doesn't print the result returned. This can be useful when a variable is bound to a sub-routine or object method which you want to call but aren't interested in the value returned. [% CALL dbi.disconnect %] [% CALL inc_page_counter(page_count) %] =head2 SET The C<SET> directive allows you to assign new values to existing variables or create new temporary variables. [% SET title = 'Hello World' %] The C<SET> keyword is also optional. [% title = 'Hello World' %] Variables may be assigned the values of other variables, unquoted numbers (2.718), literal text ('single quotes') or quoted text ("double quotes"). In the latter case, any variable references within the text will be interpolated when the string is evaluated. Variables should be prefixed by C<$>, using curly braces to explicitly scope the variable name where necessary. [% foo = 'Foo' %] # literal value 'Foo' [% bar = foo %] # value of variable 'foo' [% cost = '$100' %] # literal value '$100' [% item = "$bar: ${cost}.00" %] # value "Foo: $100.00" Multiple variables may be assigned in the same directive and are evaluated in the order specified. Thus, the above could have been written: [% foo = 'Foo' bar = foo cost = '$100' item = "$bar: ${cost}.00" %] Simple expressions can also be used, as per C<GET>. [% ten = 10 twenty = 20 thirty = twenty + ten forty = 2 * twenty fifty = 100 div 2 six = twenty mod 7 %] You can concatenate strings together using the C<'_'> underscore operator. In Perl 5, the C<.> dot is used for string concatenation, but in Perl 6, as in the Template Toolkit, the C<.> dot will be used as the method calling operator and C<'_'> underscore will be used for string concatenation. Note that the operator must be specified with surrounding whitespace which, as Larry says, is construed as a feature: [% copyright = '(C) Copyright' _ year _ ' ' _ author %] You can, of course, achieve a similar effect with double quoted string interpolation. [% copyright = "(C) Copyright $year $author" %] =head2 DEFAULT The C<DEFAULT> directive is similar to C<SET> but only updates variables that are currently undefined or have no "true" value (in the Perl sense). [% DEFAULT name = 'John Doe' id = 'jdoe' %] This can be particularly useful in common template components to ensure that some sensible default are provided for otherwise undefined variables. [% DEFAULT title = 'Hello World' bgcol = '#ffffff' %] <html> <head> <title>[% title %] ...etc... =head1 Processing Template Files and Blocks =head2 INSERT The C directive is used to insert the contents of an external file at the current position. [% INSERT myfile %] No attempt to parse or process the file is made. The contents, possibly including any embedded template directives, are inserted intact. The filename specified should be relative to one of the C directories. Absolute (i.e. starting with C) and relative (i.e. starting with C<.>) filenames may be used if the C and C options are set, respectively. Both these options are disabled by default. my $template = Template->new({ INCLUDE_PATH => '/here:/there', }); $template->process('myfile'); F: [% INSERT foo %] # looks for /here/foo then /there/foo [% INSERT /etc/passwd %] # file error: ABSOLUTE not set [% INSERT ../secret %] # file error: RELATIVE not set For convenience, the filename does not need to be quoted as long as it contains only alphanumeric characters, underscores, dots or forward slashes. Names containing any other characters should be quoted. [% INSERT misc/legalese.txt %] [% INSERT 'dos98/Program Files/stupid' %] To evaluate a variable to specify a filename, you should explicitly prefix it with a C<$> or use double-quoted string interpolation. [% language = 'en' legalese = 'misc/legalese.txt' %] [% INSERT $legalese %] # misc/legalese.txt [% INSERT "$language/$legalese" %] # en/misc/legalese.txt Multiple files can be specified using C<+> as a delimiter. All files should be unquoted names or quoted strings. Any variables should be interpolated into double-quoted strings. [% INSERT legalese.txt + warning.txt %] [% INSERT "$legalese" + warning.txt %] # requires quoting =head2 INCLUDE The C directive is used to process and include the output of another template file or block. [% INCLUDE header %] If a C of the specified name is defined in the same file, or in a file from which the current template has been called (i.e. a parent template) then it will be used in preference to any file of the same name. [% INCLUDE table %] # uses BLOCK defined below [% BLOCK table %] ...
[% END %] If a C definition is not currently visible then the template name should be a file relative to one of the C directories, or an absolute or relative file name if the C/C options are appropriately enabled. The C directive automatically quotes the filename specified, as per C described above. When a variable contains the name of the template for the C directive, it should be explicitly prefixed by C<$> or double-quoted [% myheader = 'my/misc/header' %] [% INCLUDE myheader %] # 'myheader' [% INCLUDE $myheader %] # 'my/misc/header' [% INCLUDE "$myheader" %] # 'my/misc/header' Any template directives embedded within the file will be processed accordingly. All variables currently defined will be visible and accessible from within the included template. [% title = 'Hello World' %] [% INCLUDE header %] ... F
: [% title %] output: Hello World ... Local variable definitions may be specified after the template name, temporarily masking any existing variables. Insignificant whitespace is ignored within directives so you can add variable definitions on the same line, the next line or split across several line with comments interspersed, if you prefer. [% INCLUDE table %] [% INCLUDE table title="Active Projects" %] [% INCLUDE table title = "Active Projects" bgcolor = "#80ff00" # chartreuse border = 2 %] The C directive localises (i.e. copies) all variables before processing the template. Any changes made within the included template will not affect variables in the including template. [% foo = 10 %] foo is originally [% foo %] [% INCLUDE bar %] foo is still [% foo %] [% BLOCK bar %] foo was [% foo %] [% foo = 20 %] foo is now [% foo %] [% END %] output: foo is originally 10 foo was 10 foo is now 20 foo is still 10 Technical Note: the localisation of the stash (that is, the process by which variables are copied before an C to prevent being overwritten) is only skin deep. The top-level variable namespace (hash) is copied, but no attempt is made to perform a deep-copy of other structures (hashes, arrays, objects, etc.) Therefore, a C variable referencing a hash will be copied to create a new C variable but which points to the same hash array. Thus, if you update compound variables (e.g. C) then you will change the original copy, regardless of any stash localisation. If you're not worried about preserving variable values, or you trust the templates you're including then you might prefer to use the C directive which is faster by virtue of not performing any localisation. You can specify dotted variables as "local" variables to an C directive. However, be aware that because of the localisation issues explained above (if you skipped the previous Technical Note above then you might want to go back and read it or skip this section too), the variables might not actually be "local". If the first element of the variable name already references a hash array then the variable update will affect the original variable. [% foo = { bar = 'Baz' } %] [% INCLUDE somefile foo.bar='Boz' %] [% foo.bar %] # Boz This behaviour can be a little unpredictable (and may well be improved upon in a future version). If you know what you're doing with it and you're sure that the variables in question are defined (nor not) as you expect them to be, then you can rely on this feature to implement some powerful "global" data sharing techniques. Otherwise, you might prefer to steer well clear and always pass simple (undotted) variables as parameters to C and other similar directives. If you want to process several templates in one go then you can specify each of their names (quoted or unquoted names only, no unquoted C<$variables>) joined together by C<+>. The C directive will then process them in order. [% INCLUDE html/header + "site/$header" + site/menu title = "My Groovy Web Site" %] The variable stash is localised once and then the templates specified are processed in order, all within that same variable context. This makes it slightly faster than specifying several separate C directives (because you only clone the variable stash once instead of n times), but not quite as "safe" because any variable changes in the first file will be visible in the second, third and so on. This might be what you want, of course, but then again, it might not. =head2 PROCESS The PROCESS directive is similar to C but does not perform any localisation of variables before processing the template. Any changes made to variables within the included template will be visible in the including template. [% foo = 10 %] foo is [% foo %] [% PROCESS bar %] foo is [% foo %] [% BLOCK bar %] [% foo = 20 %] changed foo to [% foo %] [% END %] output: foo is 10 changed foo to 20 foo is 20 Parameters may be specified in the C directive, but these too will become visible changes to current variable values. [% foo = 10 %] foo is [% foo %] [% PROCESS bar foo = 20 %] foo is [% foo %] [% BLOCK bar %] this is bar, foo is [% foo %] [% END %] output: foo is 10 this is bar, foo is 20 foo is 20 The C directive is slightly faster than C because it avoids the need to localise (i.e. copy) the variable stash before processing the template. As with C and C, the first parameter does not need to be quoted as long as it contains only alphanumeric characters, underscores, periods or forward slashes. A C<$> prefix can be used to explicitly indicate a variable which should be interpolated to provide the template name: [% myheader = 'my/misc/header' %] [% PROCESS myheader %] # 'myheader' [% PROCESS $myheader %] # 'my/misc/header' As with C, multiple templates can be specified, delimited by C<+>, and are processed in order. [% PROCESS html/header + my/header %] =head2 WRAPPER It's not unusual to find yourself adding common headers and footers to pages or sub-sections within a page. Something like this: [% INCLUDE section/header title = 'Quantum Mechanics' %] Quantum mechanics is a very interesting subject wish should prove easy for the layman to fully comprehend. [% INCLUDE section/footer %] [% INCLUDE section/header title = 'Desktop Nuclear Fusion for under $50' %] This describes a simple device which generates significant sustainable electrical power from common tap water by process of nuclear fusion. [% INCLUDE section/footer %] The individual template components being included might look like these: section/header:

[% title %]

section/footer:

The C directive provides a way of simplifying this a little. It encloses a block up to a matching C directive, which is first processed to generate some output. This is then passed to the named template file or C as the C variable. [% WRAPPER section title = 'Quantum Mechanics' %] Quantum mechanics is a very interesting subject wish should prove easy for the layman to fully comprehend. [% END %] [% WRAPPER section title = 'Desktop Nuclear Fusion for under $50' %] This describes a simple device which generates significant sustainable electrical power from common tap water by process of nuclear fusion. [% END %] The single 'section' template can then be defined as:

[% title %]

[% content %]

Like other block directives, it can be used in side-effect notation: [% INSERT legalese.txt WRAPPER big_bold_table %] It's also possible to specify multiple templates to a C directive. The specification order indicates outermost to innermost wrapper templates. For example, given the following template block definitions: [% BLOCK bold %][% content %][% END %] [% BLOCK italic %][% content %][% END %] the directive [% WRAPPER bold+italic %]Hello World[% END %] would generate the following output: Hello World =head2 BLOCK The C...C construct can be used to define template component blocks which can be processed with the C, C and C directives. [% BLOCK tabrow %] [% name %] [% email %] [% END %] [% PROCESS tabrow name='Fred' email='fred@nowhere.com' %] [% PROCESS tabrow name='Alan' email='alan@nowhere.com' %]
A C definition can be used before it is defined, as long as the definition resides in the same file. The block definition itself does not generate any output. [% PROCESS tmpblk %] [% BLOCK tmpblk %] This is OK [% END %] You can use an anonymous C to capture the output of a template fragment. [% julius = BLOCK %] And Caesar's spirit, ranging for revenge, With Ate by his side come hot from hell, Shall in these confines with a monarch's voice Cry 'Havoc', and let slip the dogs of war; That this foul deed shall smell above the earth With carrion men, groaning for burial. [% END %] Like a named block, it can contain any other template directives which are processed when the block is defined. The output generated by the block is then assigned to the variable C. Anonymous Cs can also be used to define block macros. The enclosing block is processed each time the macro is called. [% MACRO locate BLOCK %] The [% animal %] sat on the [% place %]. [% END %] [% locate(animal='cat', place='mat') %] # The cat sat on the mat [% locate(animal='dog', place='log') %] # The dog sat on the log =head1 Conditional Processing =head2 IF / UNLESS / ELSIF / ELSE The C and C directives can be used to process or ignore a block based on some run-time condition. [% IF frames %] [% INCLUDE frameset %] [% END %] [% UNLESS text_mode %] [% INCLUDE biglogo %] [% END %] Multiple conditions may be joined with C and/or C blocks. [% IF age < 10 %] Hello [% name %], does your mother know you're using her AOL account? [% ELSIF age < 18 %] Sorry, you're not old enough to enter (and too dumb to lie about your age) [% ELSE %] Welcome [% name %]. [% END %] The following conditional and boolean operators may be used: == != < <= > >= && || ! and or not B Unlike Perl, the C<==> and C operators perform B comparison (equivalent to Perl's C and C). The other relational operators (C>, C>, C=>, C=>) perform numeric comparison as in Perl. This means C<[% 10 == "10.0" %]> is B in the Template Toolkit (string "10" is not equal to string "10.0"), whereas it would be true in Perl. Conditions may be arbitrarily complex and are evaluated with the same precedence as in Perl. Parenthesis may be used to explicitly determine evaluation order. # ridiculously contrived complex example [% IF (name == 'admin' || uid <= 0) && mode == 'debug' %] I'm confused. [% ELSIF more > less %] That's more or less correct. [% END %] The C, C and C operator are provided as aliases for C<&&>, C<||> and C, respectively. Unlike Perl, which treats C, C and C as separate, lower-precedence versions of the other operators, the Template Toolkit performs a straightforward substitution of C for C<&&>, and so on. That means that C, C and C have the same operator precedence as C<&&>, C<||> and C. =head2 SWITCH / CASE The C / C construct can be used to perform a multi-way conditional test. The C directive expects an expression which is first evaluated and then compared against each CASE statement in turn. Each C directive should contain a single value or a list of values which should match. C may also be left blank or written as C<[% CASE DEFAULT %]> to specify a default match. Only one C matches, there is no drop-through between C statements. [% SWITCH myvar %] [% CASE 'value1' %] ... [% CASE ['value2', 'value3'] %] # multiple values ... [% CASE myhash.keys %] # ditto ... [% CASE %] # default ... [% END %] =head1 Loop Processing =head2 FOREACH The C directive will iterate through the items in a list, processing the enclosed block for each one. [% foo = 'Foo' items = [ 'one', 'two', 'three' ] %] Things: [% FOREACH thing IN [ foo 'Bar' "$foo Baz" ] %] * [% thing %] [% END %] Items: [% FOREACH i IN items %] * [% i %] [% END %] Stuff: [% stuff = [ foo "$foo Bar" ] %] [% FOREACH s IN stuff %] * [% s %] [% END %] output: Things: * Foo * Bar * Foo Baz Items: * one * two * three Stuff: * Foo * Foo Bar You can use also use C<=> instead of C if you prefer. [% FOREACH i = items %] When the C directive is used without specifying a target variable, any iterated values which are hash references will be automatically imported. [% userlist = [ { id => 'tom', name => 'Thomas' }, { id => 'dick', name => 'Richard' }, { id => 'larry', name => 'Lawrence' }, ] %] [% FOREACH user IN userlist %] [% user.id %] [% user.name %] [% END %] short form: [% FOREACH userlist %] [% id %] [% name %] [% END %] Note that this particular usage creates a localised variable context to prevent the imported hash keys from overwriting any existing variables. The imported definitions and any other variables defined in such a C loop will be lost at the end of the loop, when the previous context and variable values are restored. However, under normal operation, the loop variable remains in scope after the C loop has ended (caveat: overwriting any variable previously in scope). This is useful as the loop variable is secretly an iterator object (see below) and can be used to analyse the last entry processed by the loop. The C directive can also be used to iterate through the entries in a hash array. Each entry in the hash is returned in sorted order (based on the key) as a hash array containing 'key' and 'value' items. [% users = { tom => 'Thomas', dick => 'Richard', larry => 'Lawrence', } %] [% FOREACH u IN users %] * [% u.key %] : [% u.value %] [% END %] Output: * dick : Richard * larry : Lawrence * tom : Thomas The C directive starts the next iteration in the C loop. [% FOREACH user IN userlist %] [% NEXT IF user.isguest %] Name: [% user.name %] Email: [% user.email %] [% END %] The C directive can be used to prematurely exit the loop. C is also provided as an alias for C. [% FOREACH match IN results.nsort('score').reverse %] [% LAST IF match.score < 50 %] [% match.score %] : [% match.url %] [% END %] The C directive is implemented using the L module. A reference to the iterator object for a C directive is implicitly available in the C variable. The following methods can be called on the C iterator. size() number of elements in the list max() index number of last element (size - 1) index() index of current iteration from 0 to max() count() iteration counter from 1 to size() (i.e. index() + 1) first() true if the current iteration is the first last() true if the current iteration is the last prev() return the previous item in the list next() return the next item in the list See L for further details. Example: [% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%] [%- "
    \n" IF loop.first %]
  • [% loop.count %]/[% loop.size %]: [% item %] [%- "
\n" IF loop.last %] [% END %] Output:
  • 1/3: foo
  • 2/3: bar
  • 3/3: baz
Nested loops will work as expected, with the C variable correctly referencing the innermost loop and being restored to any previous value (i.e. an outer loop) at the end of the loop. [% FOREACH group IN grouplist; # loop => group iterator "Groups:\n" IF loop.first; FOREACH user IN group.userlist; # loop => user iterator "$loop.count: $user.name\n"; END; # loop => group iterator "End of Groups\n" IF loop.last; END %] The C plugin can also be used to explicitly create an iterator object. This can be useful within nested loops where you need to keep a reference to the outer iterator within the inner loop. The iterator plugin effectively allows you to create an iterator by a name other than C. See L for further details. [% USE giter = iterator(grouplist) %] [% FOREACH group IN giter %] [% FOREACH user IN group.userlist %] user #[% loop.count %] in group [% giter.count %] is named [% user.name %] [% END %] [% END %] =head2 WHILE The C directive can be used to repeatedly process a template block while a conditional expression evaluates true. The expression may be arbitrarily complex as per C / C. [% WHILE total < 100 %] ... [% total = calculate_new_total %] [% END %] An assignment can be enclosed in parenthesis to evaluate the assigned value. [% WHILE (user = get_next_user_record) %] [% user.name %] [% END %] The C directive can be used to start the next iteration of a C loop and C can be used to exit the loop, both as per C. The Template Toolkit uses a failsafe counter to prevent runaway C loops which would otherwise never terminate. If the loop exceeds 1000 iterations then an C exception will be thrown, reporting the error: WHILE loop terminated (> 1000 iterations) The C<$Template::Directive::WHILE_MAX> variable controls this behaviour and can be set to a higher value if necessary. =head1 Filters, Plugins, Macros and Perl =head2 FILTER The C directive can be used to post-process the output of a block. A number of standard filters are provided with the Template Toolkit. The C filter, for example, escapes the 'E', 'E' and '&' characters to prevent them from being interpreted as HTML tags or entity reference markers. [% FILTER html %] HTML text may have < and > characters embedded which you want converted to the correct HTML entities. [% END %] output: HTML text may have < and > characters embedded which you want converted to the correct HTML entities. The C directive can also follow various other non-block directives. For example: [% INCLUDE mytext FILTER html %] The C<|> character can also be used as an alias for C. [% INCLUDE mytext | html %] Multiple filters can be chained together and will be called in sequence. [% INCLUDE mytext FILTER html FILTER html_para %] or [% INCLUDE mytext | html | html_para %] Filters come in two flavours, known as 'static' or 'dynamic'. A static filter is a simple subroutine which accepts a text string as the only argument and returns the modified text. The C filter is an example of a static filter, implemented as: sub html_filter { my $text = shift; for ($text) { s/&/&/g; s//>/g; } return $text; } Dynamic filters can accept arguments which are specified when the filter is called from a template. The C filter is such an example, accepting a numerical argument which specifies the number of times that the input text should be repeated. [% FILTER repeat(3) %]blah [% END %] output: blah blah blah These are implemented as filter 'factories'. The factory subroutine is passed a reference to the current L object along with any additional arguments specified. It should then return a subroutine reference (e.g. a closure) which implements the filter. The C filter factory is implemented like this: sub repeat_filter_factory { my ($context, $iter) = @_; $iter = 1 unless defined $iter; return sub { my $text = shift; $text = '' unless defined $text; return join('\n', $text) x $iter; } } The C option, described in L, allows custom filters to be defined when a Template object is instantiated. The L method allows further filters to be defined at any time. When using a filter, it is possible to assign an alias to it for further use. This is most useful for dynamic filters that you want to re-use with the same configuration. [% FILTER echo = repeat(2) %] Is there anybody out there? [% END %] [% FILTER echo %] Mother, should I build a wall? [% END %] Output: Is there anybody out there? Is there anybody out there? Mother, should I build a wall? Mother, should I build a wall? The C directive automatically quotes the name of the filter. As with C et al, you can use a variable to provide the name of the filter, prefixed by C<$>. [% myfilter = 'html' %] [% FILTER $myfilter %] # same as [% FILTER html %] ... [% END %] A template variable can also be used to define a static filter subroutine. However, the Template Toolkit will automatically call any subroutine bound to a variable and use the value returned. Thus, the above example could be implemented as: my $vars = { myfilter => sub { return 'html' }, }; template: [% FILTER $myfilter %] # same as [% FILTER html %] ... [% END %] To define a template variable that evaluates to a subroutine reference that can be used by the C directive, you should create a subroutine that, when called automatically by the Template Toolkit, returns another subroutine reference which can then be used to perform the filter operation. Note that only static filters can be implemented in this way. my $vars = { myfilter => sub { \&my_filter_sub }, }; sub my_filter_sub { my $text = shift; # do something return $text; } template: [% FILTER $myfilter %] ... [% END %] Alternately, you can bless a subroutine reference into a class (any class will do) to fool the Template Toolkit into thinking it's an object rather than a subroutine. This will then bypass the automatic "call-a-subroutine-to-return-a-value" magic. my $vars = { myfilter => bless(\&my_filter_sub, 'anything_you_like'), }; template: [% FILTER $myfilter %] ... [% END %] Filters bound to template variables remain local to the variable context in which they are defined. That is, if you define a filter in a C block within a template that is loaded via C, then the filter definition will only exist until the end of that template when the stash is delocalised, restoring the previous variable state. If you want to define a filter which persists for the lifetime of the processor, or define additional dynamic filter factories, then you can call the L method on the current L object. See L for a complete list of available filters, their descriptions and examples of use. =head2 USE The C directive can be used to load and initialise "plugin" extension modules. [% USE myplugin %] A plugin is a regular Perl module that conforms to a particular object-oriented interface, allowing it to be loaded into and used automatically by the Template Toolkit. For details of this interface and information on writing plugins, consult L. A number of standard plugins are included with the Template Toolkit (see below and L). The names of these standard plugins are case insensitive. [% USE CGI %] # => Template::Plugin::CGI [% USE Cgi %] # => Template::Plugin::CGI [% USE cgi %] # => Template::Plugin::CGI You can also define further plugins using the C option. my $tt = Template->new({ PLUGINS => { foo => 'My::Plugin::Foo', bar => 'My::Plugin::Bar', }, }); The recommended convention is to specify these plugin names in lower case. The Template Toolkit first looks for an exact case-sensitive match and then tries the lower case conversion of the name specified. [% USE Foo %] # look for 'Foo' then 'foo' If you define all your C with lower case names then they will be located regardless of how the user specifies the name in the C directive. If, on the other hand, you define your C with upper or mixed case names then the name specified in the C directive must match the case exactly. If the plugin isn't defined in either the standard plugins (C<$Template::Plugins::STD_PLUGINS>) or via the C option, then the C is searched. In this case the plugin name I case-sensitive. It is appended to each of the C module namespaces in turn (default: C) to construct a full module name which it attempts to locate and load. Any periods, 'C<.>', in the name will be converted to 'C<::>'. [% USE MyPlugin %] # => Template::Plugin::MyPlugin [% USE Foo.Bar %] # => Template::Plugin::Foo::Bar The C option (disabled by default) provides a further way by which external Perl modules may be loaded. If a regular Perl module (i.e. not a C or other module relative to some C) supports an object-oriented interface and a C constructor then it can be loaded and instantiated automatically. The following trivial example shows how the IO::File module might be used. [% USE file = IO.File('/tmp/mydata') %] [% WHILE (line = file.getline) %] [% END %] Any additional parameters supplied in parenthesis after the plugin name will be also be passed to the C constructor. A reference to the current L object is passed as the first parameter. [% USE MyPlugin('foo', 123) %] equivalent to: Template::Plugin::MyPlugin->new($context, 'foo', 123); The only exception to this is when a module is loaded via the C option. In this case the C<$context> reference is I passed to the C constructor. This is based on the assumption that the module is a regular Perl module rather than a Template Toolkit plugin so isn't expecting a context reference and wouldn't know what to do with it anyway. Named parameters may also be specified. These are collated into a hash which is passed by reference as the last parameter to the constructor, as per the general code calling interface. [% USE url('/cgi-bin/foo', mode='submit', debug=1) %] equivalent to: Template::Plugin::URL->new( $context, '/cgi-bin/foo' { mode => 'submit', debug => 1 } ); The plugin may represent any data type; a simple variable, hash, list or code reference, but in the general case it will be an object reference. Methods can be called on the object (or the relevant members of the specific data type) in the usual way: [% USE table(mydata, rows=3) %] [% FOREACH row IN table.rows %] [% FOREACH item IN row %] [% item %] [% END %] [% END %] An alternative name may be provided for the plugin by which it can be referenced: [% USE scores = table(myscores, cols=5) %] [% FOREACH row IN scores.rows %] ... [% END %] You can use this approach to create multiple plugin objects with different configurations. This example shows how the L plugin is used to create sub-routines bound to variables for formatting text as per C. [% USE bold = format('%s') %] [% USE ital = format('%s') %] [% bold('This is bold') %] [% ital('This is italic') %] Output: This is bold This is italic This next example shows how the L plugin can be used to build dynamic URLs from a base part and optional query parameters. [% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %] ... ... ... The L plugin is an example of one which delegates to another Perl module. In this case, to Lincoln Stein's C module. All of the methods provided by the C module are available via the plugin. [% USE CGI; CGI.start_form; CGI.checkbox_group( name = 'colours', values = [ 'red' 'green' 'blue' ] ); CGI.popup_menu( name = 'items', values = [ 'foo' 'bar' 'baz' ] ); CGI.end_form %] See L for more information on the plugins distributed with the toolkit or available from CPAN. =head2 MACRO The C directive allows you to define a directive or directive block which is then evaluated each time the macro is called. [% MACRO header INCLUDE header %] Calling the macro as: [% header %] is then equivalent to: [% INCLUDE header %] Macros can be passed named parameters when called. These values remain local to the macro. [% header(title='Hello World') %] equivalent to: [% INCLUDE header title='Hello World' %] A C definition may include parameter names. Values passed to the macros are then mapped to these local variables. Other named parameters may follow these. [% MACRO header(title) INCLUDE header %] [% header('Hello World') %] [% header('Hello World', bgcol='#123456') %] equivalent to: [% INCLUDE header title='Hello World' %] [% INCLUDE header title='Hello World' bgcol='#123456' %] Here's another example, defining a macro for display numbers in comma-delimited groups of 3, using the chunk and join virtual method. [% MACRO number(n) GET n.chunk(-3).join(',') %] [% number(1234567) %] # 1,234,567 A C may precede any directive and must conform to the structure of the directive. [% MACRO header IF frames %] [% INCLUDE frames/header %] [% ELSE %] [% INCLUDE header %] [% END %] [% header %] A C may also be defined as an anonymous C. The block will be evaluated each time the macro is called. [% MACRO header BLOCK %] ...content... [% END %] [% header %] If you've got the C option set, then you can even define a C as a C block (see below): [% MACRO triple(n) PERL %] my $n = $stash->get('n'); print $n * 3; [% END -%] =head2 PERL (for the advanced reader) The C directive is used to mark the start of a block which contains Perl code for evaluation. The C option must be enabled for Perl code to be evaluated or a C exception will be thrown with the message 'C'. Perl code is evaluated in the C package. The C<$context> package variable contains a reference to the current L object. This can be used to access the functionality of the Template Toolkit to process other templates, load plugins, filters, etc. See L for further details. [% PERL %] print $context->include('myfile'); [% END %] The L<$stash> variable contains a reference to the top-level stash object which manages template variables. Through this, variable values can be retrieved and updated. See L for further details. [% PERL %] $stash->set(foo => 'bar'); print "foo value: ", $stash->get('foo'); [% END %] Output: foo value: bar Output is generated from the C block by calling C. Note that the C handle is selected (tied to an output buffer) instead of C. [% PERL %] print "foo\n"; # OK print PERLOUT "bar\n"; # OK, same as above print Template::Perl::PERLOUT "baz\n"; # OK, same as above print STDOUT "qux\n"; # WRONG! [% END %] The C block may contain other template directives. These are processed before the Perl code is evaluated. [% name = 'Fred Smith' %] [% PERL %] print "[% name %]\n"; [% END %] Thus, the Perl code in the above example is evaluated as: print "Fred Smith\n"; Exceptions may be thrown from within C blocks using C. They will be correctly caught by enclosing C blocks. [% TRY %] [% PERL %] die "nothing to live for\n"; [% END %] [% CATCH %] error: [% error.info %] [% END %] output: error: nothing to live for =head2 RAWPERL (for the very advanced reader) The Template Toolkit parser reads a source template and generates the text of a Perl subroutine as output. It then uses C to evaluate it into a subroutine reference. This subroutine is then called to process the template, passing a reference to the current L object through which the functionality of the Template Toolkit can be accessed. The subroutine reference can be cached, allowing the template to be processed repeatedly without requiring any further parsing. For example, a template such as: [% PROCESS header %] The [% animal %] sat on the [% location %] [% PROCESS footer %] is converted into the following Perl subroutine definition: sub { my $context = shift; my $stash = $context->stash; my $output = ''; my $error; eval { BLOCK: { $output .= $context->process('header'); $output .= "The "; $output .= $stash->get('animal'); $output .= " sat on the "; $output .= $stash->get('location'); $output .= $context->process('footer'); $output .= "\n"; } }; if ($@) { $error = $context->catch($@, \$output); die $error unless $error->type eq 'return'; } return $output; } To examine the Perl code generated, such as in the above example, set the C<$Template::Parser::DEBUG> package variable to any true value. You can also set the C<$Template::Directive::PRETTY> variable true to have the code formatted in a readable manner for human consumption. The source code for each generated template subroutine will be printed to C on compilation (i.e. the first time a template is used). $Template::Parser::DEBUG = 1; $Template::Directive::PRETTY = 1; $template->process($file, $vars) || die $template->error(), "\n"; The C ... C construct allows Perl code to be embedded into a template when the C option is set. It is evaluated at "runtime" using C each time the template subroutine is called. This is inherently flexible, but not as efficient as it could be, especially in a persistent server environment where a template may be processed many times. The C directive allows you to write Perl code that is integrated directly into the generated Perl subroutine text. It is evaluated once at compile time and is stored in cached form as part of the compiled template subroutine. This makes C blocks more efficient than C blocks. The downside is that you must code much closer to the metal. For example, in a C block you can call L to generate some output. C blocks don't afford such luxury. The code is inserted directly into the generated subroutine text and should conform to the convention of appending to the C<$output> variable. [% PROCESS header %] [% RAWPERL %] $output .= "Some output\n"; ... $output .= "Some more output\n"; [% END %] The critical section of the generated subroutine for this example would then look something like: ... eval { BLOCK: { $output .= $context->process('header'); $output .= "\n"; $output .= "Some output\n"; ... $output .= "Some more output\n"; $output .= "\n"; } }; ... As with C blocks, the L<$context|Template::Context> and L<$stash|Template::Stash> references are pre-defined and available for use within C code. =head1 Exception Handling and Flow Control =head2 TRY / THROW / CATCH / FINAL (more advanced material) The Template Toolkit supports fully functional, nested exception handling. The C directive introduces an exception handling scope which continues until the matching C directive. Any errors that occur within that block will be caught and can be handled by one of the C blocks defined. [% TRY %] ...blah...blah... [% CALL somecode %] ...etc... [% INCLUDE someblock %] ...and so on... [% CATCH %] An error occurred! [% END %] Errors are raised as exceptions (objects of the L class) which contain two fields: C and C. The exception C is used to indicate the kind of error that occurred. It is a simple text string which can contain letters, numbers, 'C<_>' or 'C<.>'. The C field contains an error message indicating what actually went wrong. Within a catch block, the exception object is aliased to the C variable. You can access the C and C fields directly. [% mydsn = 'dbi:MySQL:foobar' %] ... [% TRY %] [% USE DBI(mydsn) %] [% CATCH %] ERROR! Type: [% error.type %] Info: [% error.info %] [% END %] output (assuming a non-existent database called 'C'): ERROR! Type: DBI Info: Unknown database "foobar" The C variable can also be specified by itself and will return a string of the form "C<$type error - $info>". ... [% CATCH %] ERROR: [% error %] [% END %] Output: ERROR: DBI error - Unknown database "foobar" Each C block may be specified with a particular exception type denoting the kind of error that it should catch. Multiple C blocks can be provided to handle different types of exception that may be thrown in the C block. A C block specified without any type, as in the previous example, is a default handler which will catch any otherwise uncaught exceptions. This can also be specified as C<[% CATCH DEFAULT %]>. [% TRY %] [% INCLUDE myfile %] [% USE DBI(mydsn) %] [% CALL somecode %] [% CATCH file %] File Error! [% error.info %] [% CATCH DBI %] [% INCLUDE database/error.html %] [% CATCH %] [% error %] [% END %] Remember that you can specify multiple directives within a single tag, each delimited by 'C<;>'. So the above example can be written more concisely as: [% TRY; INCLUDE myfile; USE DBI(mydsn); CALL somecode; CATCH file; "File Error! $error.info"; CATCH DBI; INCLUDE database/error.html; CATCH; error; END %] The C plugin throws exceptions of the C type (in case that wasn't already obvious). The other specific exception caught here is of the C type. A C exception is automatically thrown by the Template Toolkit when it can't find a file, or fails to load, parse or process a file that has been requested by an C, C, C or C directive. If C can't be found in the example above, the C<[% INCLUDE myfile %]> directive will raise a C exception which is then caught by the C<[% CATCH file %]> block. The output generated would be: File Error! myfile: not found Note that the C option (disabled by default) allows you to specify a default file to be used any time a template file can't be found. This will prevent file exceptions from ever being raised when a non-existent file is requested (unless, of course, the C file your specify doesn't exist). Errors encountered once the file has been found (i.e. read error, parse error) will be raised as file exceptions as per usual. Uncaught exceptions (i.e. if the C block doesn't have a type specific or default C handler) may be caught by enclosing C blocks which can be nested indefinitely across multiple templates. If the error isn't caught at any level then processing will stop and the Template L method will return a false value to the caller. The relevant L object can be retrieved by calling the L method. [% TRY %] ... [% TRY %] [% INCLUDE $user.header %] [% CATCH file %] [% INCLUDE header %] [% END %] ... [% CATCH DBI %] [% INCLUDE database/error.html %] [% END %] In this example, the inner C block is used to ensure that the first C directive works as expected. We're using a variable to provide the name of the template we want to include, C, and it's possible this contains the name of a non-existent template, or perhaps one containing invalid template directives. If the C fails with a C error then we C it in the inner block and C the default C
file instead. Any C errors that occur within the scope of the outer C block will be caught in the relevant C block, causing the C template to be processed. Note that included templates inherit all currently defined template variable so these error files can quite happily access the variable to retrieve information about the currently caught exception. For example, the C template might look like this:

Database Error

A database error has occurred: [% error.info %] You can also specify a C block. This is always processed regardless of the outcome of the C and/or C blocks. If an exception is uncaught then the C block is processed before jumping to the enclosing block or returning to the caller. [% TRY %] ... [% CATCH this %] ... [% CATCH that %] ... [% FINAL %] All done! [% END %] The output from the C block is left intact up to the point where an exception occurs. For example, this template: [% TRY %] This gets printed [% THROW food 'carrots' %] This doesn't [% CATCH food %] culinary delights: [% error.info %] [% END %] generates the following output: This gets printed culinary delights: carrots The C directive can be used in a C or C block to clear any output created in the C block. [% TRY %] This gets printed [% THROW food 'carrots' %] This doesn't [% CATCH food %] [% CLEAR %] culinary delights: [% error.info %] [% END %] Output: culinary delights: carrots Exception types are hierarchical, with each level being separated by the familiar dot operator. A C exception is a more specific kind of C error. Similarly, an C is a more specific kind of C type which itself is also a C error. A C handler that specifies a general exception type (such as C or C) will also catch more specific types that have the same prefix as long as a more specific handler isn't defined. Note that the order in which C handlers are defined is irrelevant; a more specific handler will always catch an exception in preference to a more generic or default one. [% TRY %] ... [% CATCH DBI ; INCLUDE database/error.html ; CATCH DBI.connect ; INCLUDE database/connect.html ; CATCH ; INCLUDE error.html ; END %] In this example, a C error has it's own handler, a more general C block is used for all other C or C errors and a default handler catches everything else. Exceptions can be raised in a template using the C directive. The first parameter is the exception type which doesn't need to be quoted (but can be, it's the same as C) followed by the relevant error message which can be any regular value such as a quoted string, variable, etc. [% THROW food "Missing ingredients: $recipe.error" %] [% THROW user.login 'no user id: please login' %] [% THROW $myerror.type "My Error: $myerror.info" %] It's also possible to specify additional positional or named parameters to the C directive if you want to pass more than just a simple message back as the error info field. [% THROW food 'eggs' 'flour' msg='Missing Ingredients' %] In this case, the error C field will be a hash array containing the named arguments and an C item which contains a list of the positional arguments. type => 'food', info => { msg => 'Missing Ingredients', args => ['eggs', 'flour'], } In addition to specifying individual positional arguments as C<[% error.info.args.n %]>, the C hash contains keys directly pointing to the positional arguments, as a convenient shortcut. [% error.info.0 %] # same as [% error.info.args.0 %] Exceptions can also be thrown from Perl code which you've bound to template variables, or defined as a plugin or other extension. To raise an exception, call C passing a reference to a L object as the argument. This will then be caught by any enclosing C blocks from where the code was called. use Template::Exception; ... my $vars = { foo => sub { # ... do something ... die Template::Exception->new('myerr.naughty', 'Bad, bad error'); }, }; Template: [% TRY %] [% foo %] [% CATCH myerr ; "Error: $error" ; END %] Output: Error: myerr.naughty error - Bad, bad error The C field can also be a reference to another object or data structure, if required. die Template::Exception->new('myerror', { module => 'foo.pl', errors => [ 'bad permissions', 'naughty boy' ], }); Later, in a template: [% TRY %] ... [% CATCH myerror %] [% error.info.errors.size or 'no'; error.info.errors.size == 1 ? ' error' : ' errors' %] in [% error.info.module %]: [% error.info.errors.join(', ') %]. [% END %] Generating the output: 2 errors in foo.pl: bad permissions, naughty boy. You can also call C with a single string, as is common in much existing Perl code. This will automatically be converted to an exception of the 'C' type (that's the literal string 'C', not the undefined value). If the string isn't terminated with a newline then Perl will append the familiar C<" at $file line $line"> message. sub foo { # ... do something ... die "I'm sorry, Dave, I can't do that\n"; } If you're writing a plugin, or some extension code that has the current L in scope (you can safely skip this section if this means nothing to you) then you can also raise an exception by calling the context L method. You can pass it an L object reference, a pair of C<($type, $info)> parameters or just an C<$info> string to create an exception of 'C' type. $context->throw($e); # exception object $context->throw('Denied'); # 'undef' type $context->throw('user.passwd', 'Bad Password'); =head2 NEXT The C directive can be used to start the next iteration of a C or C loop. [% FOREACH user IN users %] [% NEXT IF user.isguest %] Name: [% user.name %] Email: [% user.email %] [% END %] =head2 LAST The C directive can be used to prematurely exit a C or C loop. [% FOREACH user IN users %] Name: [% user.name %] Email: [% user.email %] [% LAST IF some.condition %] [% END %] C can also be used as an alias for C. =head2 RETURN The C directive can be used to stop processing the current template and return to the template from which it was called, resuming processing at the point immediately after the C, C or C directive. If there is no enclosing template then the Template L method will return to the calling code with a true value. Before [% INCLUDE half_wit %] After [% BLOCK half_wit %] This is just half... [% RETURN %] ...a complete block [% END %] Output: Before This is just half... After =head2 STOP The C directive can be used to indicate that the processor should stop gracefully without processing any more of the template document. This is a planned stop and the Template L method will return a B value to the caller. This indicates that the template was processed successfully according to the directives within it. [% IF something.terrible.happened %] [% INCLUDE fatal/error.html %] [% STOP %] [% END %] [% TRY %] [% USE DBI(mydsn) %] ... [% CATCH DBI.connect %]

Cannot connect to the database: [% error.info %]

We apologise for the inconvenience.

[% INCLUDE footer %] [% STOP %] [% END %] =head2 CLEAR The C directive can be used to clear the output buffer for the current enclosing block. It is most commonly used to clear the output generated from a C block up to the point where the error occurred. [% TRY %] blah blah blah # this is normally left intact [% THROW some 'error' %] # up to the point of error ... [% CATCH %] [% CLEAR %] # clear the TRY output [% error %] # print error string [% END %] =head1 Miscellaneous =head2 META The C directive allows simple metadata items to be defined within a template. These are evaluated when the template is parsed and as such may only contain simple values (e.g. it's not possible to interpolate other variables values into C variables). [% META title = 'The Cat in the Hat' author = 'Dr. Seuss' version = 1.23 %] The C