1Template::Manual::IntroU(s3e)r Contributed Perl DocumentaTteimopnlate::Manual::Intro(3)
2
3
4

NAME

6       Template::Manual::Intro - Introduction to the Template Toolkit
7

Introduction

9       The Template Toolkit is a collection of Perl modules which implement a
10       fast, flexible, powerful and extensible template processing system.  It
11       is most often used for generating dynamic web content, although it can
12       be used equally well for processing any kind of text documents.
13
14       At the simplest level it provides an easy way to process template
15       files, filling in embedded variable references with their equivalent
16       values.  Here's an example of a template.
17
18           Dear [% name %],
19
20           It has come to our attention that your account is in
21           arrears to the sum of [% debt %].
22
23           Please settle your account before [% deadline %] or we
24           will be forced to revoke your Licence to Thrill.
25
26           The Management.
27
28       By default, template directives are embedded within the character
29       sequences "[%" ... "%]" but you can change these and various other
30       options to configure how the Template Toolkit looks, feels and works.
31       You can set the "INTERPOLATE" option, for example, if you prefer to
32       embed your variables in Perl style:
33
34           Dear $name,
35
36           It has come to our attention that your account is in
37           arrears to the sum of $debt.
38
39           ...etc...
40

The Template Perl Module

42       The Template Perl module is the front end to the Template Toolkit for
43       Perl programmers, providing access to the full range of functionality
44       through a single module with a simple interface. It loads the other
45       modules as required and instantiates a default set of objects to handle
46       subsequent template processing requests. Configuration parameters may
47       be passed to the Template constructor method, new(), which are then
48       used to configure the generate object.
49
50           use Template;
51
52           my $tt = Template->new({
53               INCLUDE_PATH => '/usr/local/templates',
54               INTERPOLATE  => 1,
55           }) || die "$Template::ERROR\n";
56
57       The Template object implements a process() method for processing
58       template files or text. The name of the input template (or various
59       other sources) is passed as the first argument, followed by a reference
60       to a hash array of variable definitions for substitution in the
61       template.
62
63           my $vars = {
64               name     => 'Count Edward van Halen',
65               debt     => '3 riffs and a solo',
66               deadline => 'the next chorus',
67           };
68
69           $tt->process('letters/overdrawn', $vars)
70               || die $tt->error(), "\n";
71
72       The process() method returns a true value (1) on success and prints the
73       template output to "STDOUT", by default. On error, the process() method
74       returns a false value ("undef").  The error() method can then be called
75       to retrieve details of the error.
76

Component Based Content Construction

78       A number of special directives are provided, such as "INSERT",
79       "INCLUDE" and "PROCESS", which allow content to be built up from
80       smaller template components. This permits a modular approach to
81       building a web site or other content repository, promoting reusability,
82       cross-site consistency, ease of construction and subsequent
83       maintenance. Common elements such as headers, footers, menu bars,
84       tables, and so on, can be created as separate template files which can
85       then be processed into other documents as required. All defined
86       variables are inherited by these templates along with any additional
87       "local" values specified.
88
89           [% PROCESS header
90                title = "The Cat Sat on the Mat"
91           %]
92
93           [% PROCESS menu %]
94
95           The location of the missing feline has now been established.
96           Thank you for your assistance.
97
98           [% INSERT legal/disclaimer %]
99
100           [% PROCESS footer %]
101
102       You can also define a template as a BLOCK within the same file and
103       PROCESS it just like any other template file.  This can be invaluable
104       for building up repetitive elements such as tables, menus, etc.
105
106           [% BLOCK tabrow %]
107              <tr><td>[% name %]</td><td>[% email %]</td></tr>
108           [% END %]
109
110           <table>
111           [% PROCESS tabrow name="tom"   email="tom@here.org"    %]
112           [% PROCESS tabrow name="dick"  email="disk@there.org"  %]
113           [% PROCESS tabrow name="larry" email="larry@where.org" %]
114           </table>
115

Data and Code Binding

117       One of the key features that sets the Template Toolkit apart from other
118       template processors is the ability to bind template variables to any
119       kind of Perl data: scalars, lists, hash arrays, sub-routines and
120       objects.
121
122           my $vars = {
123               root   => 'http://here.com/there',
124               menu   => [ 'modules', 'authors', 'scripts' ],
125               client => {
126                   name => 'Doctor Joseph von Satriani',
127                   id   => 'JVSAT',
128               },
129               checkout => sub { my $total = shift; ...; return $something },
130               shopcart => My::Cool::Shopping::Cart->new(),
131           };
132
133       The Template Toolkit will automatically Do The Right Thing to access
134       the data in an appropriate manner to return some value which can then
135       be output. The dot operator '"."' is used to access into lists and
136       hashes or to call object methods. The "FOREACH" directive is provided
137       for iterating through lists, and various logical tests are available
138       using directives such as "IF", "UNLESS", "ELSIF", "ELSE", "SWITCH",
139       "CASE", etc.
140
141           [% FOREACH section = menu %]
142              <a href="[% root %]/[% section %]/index.html">[% section %]</a>
143           [% END %]
144
145           <b>Client</a>: [% client.name %] (id: [% client.id %])
146
147           [% IF shopcart.nitems %]
148              Your shopping cart contains the following items:
149              <ul>
150              [% FOREACH item = shopcart.contents %]
151                <li>[% item.name %] : [% item.qty %] @ [% item.price %]
152              [% END %]
153              </ul>
154
155              [% checkout(shopcart.total) %]
156
157           [% ELSE %]
158              No items currently in shopping cart.
159           [% END %]
160

Advanced Features: Filters, Macros, Exceptions, Plugins

162       The Template Toolkit also provides a number of additional directives
163       for advanced processing and programmatical functionality.  It supports
164       output filters (FILTER), allows custom macros to be defined (MACRO),
165       has a fully-featured exception handling system (TRY, THROW, CATCH,
166       FINAL) and supports a plugin architecture (USE) which allows special
167       plugin modules and even regular Perl modules to be loaded and used with
168       the minimum of fuss.  The Template Toolkit is "just" a template
169       processor but you can trivially extend it to incorporate the
170       functionality of any Perl module you can get your hands on.  Thus, it
171       is also a scalable and extensible template framework, ideally suited
172       for managing the presentation layer for application servers, content
173       management systems and other web applications.
174

Separating Presentation and Application Logic

176       Rather than embedding Perl code or some other scripting language
177       directly into template documents, it encourages you to keep functional
178       components (i.e. Perl code) separate from presentation components (e.g.
179       HTML templates).  The template variables provide the interface between
180       the two layers, allowing data to be generated in code and then passed
181       to a template component for displaying (pipeline model) or for sub-
182       routine or object references to be bound to variables which can then be
183       called from the template as and when required (callback model).
184
185       The directives that the Template Toolkit provide implement their own
186       mini programming language, but they're not really designed for serious,
187       general purpose programming.  Perl is a far more appropriate language
188       for that.  If you embed application logic (e.g. Perl or other scripting
189       language fragments) in HTML templates then you risk losing the clear
190       separation of concerns between functionality and presentation.  It
191       becomes harder to maintain the two elements in isolation and more
192       difficult, if not impossible, to reuse code or presentation elements by
193       themselves.  It is far better to write your application code in
194       separate Perl modules, libraries or scripts and then use templates to
195       control how the resulting data is presented as output.  Thus you should
196       think of the Template Toolkit language as a set of layout directives
197       for displaying data, not calculating it.
198
199       Having said that, the Template Toolkit doesn't force you into one
200       approach or the other.  It attempts to be pragmatic rather than
201       dogmatic in allowing you to do whatever best gets the job done.  Thus,
202       if you enable the EVAL_PERL option then you can happily embed real Perl
203       code in your templates within PERL ... END directives.
204

Performance

206       The Template Toolkit uses a fast YACC-like parser which compiles
207       templates into Perl code for maximum runtime efficiency.  It also has
208       an advanced caching mechanism which manages in-memory and on-disk (i.e.
209       persistent) versions of compiled templates.  The modules that comprise
210       the toolkit are highly configurable and the architecture around which
211       they're built is designed to be extensible.  The Template Toolkit
212       provides a powerful framework around which content creation and
213       delivery systems can be built while also providing a simple interface
214       through the Template front-end module for general use.
215
216
217
218perl v5.10.1                      2008-11-13        Template::Manual::Intro(3)
Impressum