1Template::Manual::IntroU(s3e)r Contributed Perl DocumentaTteimopnlate::Manual::Intro(3)
2
3
4
6 Template::Manual::Intro - Introduction to the Template Toolkit
7
9 The Template Toolkit is a collection of modules which implement a fast,
10 flexible, powerful and extensible template processing system. It was
11 originally designed and remains primarily useful for generating dynamic
12 web content, but it can be used equally well for processing any kind of
13 text documents. This POD documentation is all generated using the Tem‐
14 plate Toolkit batch mode utility ttree, for example.
15
16 At the simplest level it provides an easy way to process template
17 files, filling in embedded variable references with their equivalent
18 values.
19
20 Dear [% name %],
21
22 It has come to our attention that your account is in
23 arrears to the sum of [% debt %].
24
25 Please settle your account before [% deadline %] or we
26 will be forced to revoke your Licence to Thrill.
27
28 The Management.
29
30 By default, template directives are embedded within the character
31 sequences '[%' ... '%]' but you can change these and various other
32 options to configure how the Template Toolkit looks, feels and works.
33 You can set the INTERPOLATE option, for example, if you prefer to embed
34 your variables in Perl style:
35
36 Dear $name,
37
38 It has come to our attention that your account is in
39 arrears to the sum of $debt.
40 ...
41
42 Template.pm
43
44 The Template.pm module is the front end to the Template Toolkit, pro‐
45 viding access to the full range of functionality through a single mod‐
46 ule with a simple interface. It loads the other modules as required
47 and instantiates a default set of objects to handle subsequent template
48 processing requests. Configuration parameters may be passed to the
49 Template.pm constructor, new(), which are then used to configure the
50 underlying objects.
51
52 use Template;
53
54 my $tt = Template->new({
55 INCLUDE_PATH => '/usr/local/templates',
56 INTERPOLATE => 1,
57 }) ⎪⎪ die "$Template::ERROR\n";
58
59 The Template object implements a process() method for processing tem‐
60 plate files or text. The name of the input template (or various other
61 sources) is passed as the first argument, followed by a reference to a
62 hash array of variable definitions for substitution in the template.
63
64 my $vars = {
65 name => 'Count Edward van Halen',
66 debt => '3 riffs and a solo',
67 deadline => 'the next chorus',
68 };
69
70 $tt->process('letters/overdrawn', $vars)
71 ⎪⎪ die $tt->error(), "\n";
72
73 The process() method returns true (1) on success and prints the tem‐
74 plate output to STDOUT, by default. On error, the process() method
75 returns false (undef). The error() method can then be called to
76 retrieve details of the error.
77
78 Component Based Content Construction
79
80 A number of special directives are provided, such as INSERT, INCLUDE
81 and PROCESS, which allow content to be built up from smaller template
82 components. This permits a modular approach to building a web site or
83 other content repository, promoting reusability, cross-site consis‐
84 tency, ease of construction and subsequent maintenance. Common ele‐
85 ments such as headers, footers, menu bars, tables, and so on, can be
86 created as separate template files which can then be processed into
87 other documents as required. All defined variables are inherited by
88 these templates along with any additional "local" values specified.
89
90 [% PROCESS header
91 title = "The Cat Sat on the Mat"
92 %]
93
94 [% PROCESS menu %]
95
96 The location of the missing feline has now been established.
97 Thank you for your assistance.
98
99 [% INSERT legal/disclaimer %]
100
101 [% PROCESS footer %]
102
103 You can also define a template as a BLOCK within the same file and
104 PROCESS it just like any other template file. This can be invaluable
105 for building up repetitive elements such as tables, menus, etc.
106
107 [% BLOCK tabrow %]
108 <tr><td>[% name %]</td><td>[% email %]</td></tr>
109 [% END %]
110
111 <table>
112 [% PROCESS tabrow name="tom" email="tom@here.org" %]
113 [% PROCESS tabrow name="dick" email="disk@there.org" %]
114 [% PROCESS tabrow name="larry" email="larry@where.org" %]
115 </table>
116
117 Data and Code Binding
118
119 One of the key features that sets the Template Toolkit apart from other
120 template processors is the ability to bind template variables to any
121 kind of Perl data: scalars, lists, hash arrays, sub-routines and
122 objects.
123
124 my $vars = {
125 root => 'http://here.com/there',
126 menu => [ 'modules', 'authors', 'scripts' ],
127 client => {
128 name => 'Doctor Joseph von Satriani',
129 id => 'JVSAT',
130 },
131 checkout => sub { my $total = shift; ...; return $something },
132 shopcart => My::Cool::Shopping::Cart->new(),
133 };
134
135 The Template Toolkit will automatically Do The Right Thing to access
136 the data in an appropriate manner to return some value which can then
137 be output. The dot operator '.' is used to access into lists and
138 hashes or to call object methods. The FOREACH directive is provided
139 for iterating through lists, and various logical tests are available
140 using directives such as IF, UNLESS, ELSIF, ELSE, SWITCH, CASE, etc.
141
142 [% FOREACH section = menu %]
143 <a href="[% root %]/[% section %]/index.html">[% section %]</a>
144 [% END %]
145
146 <b>Client</a>: [% client.name %] (id: [% client.id %])
147
148 [% IF shopcart.nitems %]
149 Your shopping cart contains the following items:
150 <ul>
151 [% FOREACH item = shopcart.contents %]
152 <li>[% item.name %] : [% item.qty %] @ [% item.price %]
153 [% END %]
154 </ul>
155
156 [% checkout(shopcart.total) %]
157
158 [% ELSE %]
159 No items currently in shopping cart.
160 [% END %]
161
162 Advanced Features: Filters, Macros, Exceptions, Plugins
163
164 The Template Toolkit also provides a number of additional directives
165 for advanced processing and programmatical functionality. It supports
166 output filters (FILTER), allows custom macros to be defined (MACRO),
167 has a fully-featured exception handling system (TRY, THROW, CATCH,
168 FINAL) and supports a plugin architecture (USE) which allows special
169 plugin modules and even regular Perl modules to be loaded and used with
170 the minimum of fuss. The Template Toolkit is "just" a template proces‐
171 sor but you can trivially extend it to incorporate the functionality of
172 any Perl module you can get your hands on. Thus, it is also a scalable
173 and extensible template framework, ideally suited for managing the pre‐
174 sentation layer for application servers, content management systems and
175 other web applications.
176
177 Separating Presentation and Application Logic
178
179 Rather than embedding Perl code or some other scripting language
180 directly into template documents, it encourages you to keep functional
181 components (i.e. Perl code) separate from presentation components (e.g.
182 HTML templates). The template variables provide the interface between
183 the two layers, allowing data to be generated in code and then passed
184 to a template component for displaying (pipeline model) or for sub-rou‐
185 tine or object references to be bound to variables which can then be
186 called from the template as and when required (callback model).
187
188 The directives that the Template Toolkit provide implement their own
189 mini programming language, but they're not really designed for serious,
190 general purpose programming. Perl is a far more appropriate language
191 for that. If you embed application logic (e.g. Perl or other scripting
192 language fragments) in HTML templates then you risk losing the clear
193 separation of concerns between functionality and presentation. It
194 becomes harder to maintain the two elements in isolation and more dif‐
195 ficult, if not impossible, to reuse code or presentation elements by
196 themselves. It is far better to write your application code in sepa‐
197 rate Perl modules, libraries or scripts and then use templates to con‐
198 trol how the resulting data is presented as output. Thus you should
199 think of the Template Toolkit language as a set of layout directives
200 for displaying data, not calculating it.
201
202 Having said that, the Template Toolkit doesn't force you into one
203 approach or the other. It attempts to be pragmatic rather than dog‐
204 matic in allowing you to do whatever best gets the job done. Thus, if
205 you enable the EVAL_PERL option then you can happily embed real Perl
206 code in your templates within PERL ... END directives.
207
208 Performance
209
210 The Template Toolkit uses a fast YACC-like parser which compiles tem‐
211 plates into Perl code for maximum runtime efficiency. It also has an
212 advanced caching mechanism which manages in-memory and on-disk (i.e.
213 persistent) versions of compiled templates. The modules that comprise
214 the toolkit are highly configurable and the architecture around which
215 they're built is designed to be extensible. The Template Toolkit pro‐
216 vides a powerful framework around which content creation and delivery
217 systems can be built while also providing a simple interface through
218 the Template front-end module for general use.
219
221 Andy Wardley <abw@wardley.org>
222
223 <http://wardley.org/⎪http://wardley.org/>
224
226 Template Toolkit version 2.18, released on 09 February 2007.
227
229 Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
230
231 This module is free software; you can redistribute it and/or modify it
232 under the same terms as Perl itself.
233
234
235
236perl v5.8.8 2007-02-09 Template::Manual::Intro(3)