1Template::Tutorial::WebU(s3e)r Contributed Perl DocumentaTteimopnlate::Tutorial::Web(3)
2
3
4
6 Template::Tutorial::Web - Generating Web Content Using the Template
7 Toolkit
8
10 This tutorial document provides a introduction to the Template Toolkit
11 and demonstrates some of the typical ways it may be used for generating
12 web content. It covers the generation of static pages from templates
13 using the tpage and ttree scripts and then goes on to show dynamic con‐
14 tent generation using CGI scripts and Apache/mod_perl handlers.
15
16 Various features of the Template Toolkit are introduced and described
17 briefly and explained by use of example. For further information, see
18 Template, Template::Manual and the various sections within it. e.g.
19
20 perldoc Template # Template.pm module usage
21 perldoc Template::Manual # index to manual
22 perldoc Template::Manual::Config # e.g. configuration options
23
24 The documentation is now also distributed in HTML format (or rather, in
25 the form of HTML templates). See the 'docs' sub-directory of the dis‐
26 tribution for further information on building the HTML documentation.
27
28 If you're already reading this as part of the HTML documentation, then
29 you don't need to worry about all that. You can have a seat, sit back.
30 back and enjoy the rest of the tutorial...
31
33 The Template Toolkit is a set of Perl modules which collectively imple‐
34 ment a template processing system. In this context, a template is a
35 text document containing special markup tags called 'directives'. A
36 directive is an instruction for the template processor to perform some
37 action and substitute the result into the document in place of the
38 original directive. Directives include those to define or insert a
39 variable value, iterate through a list of values (FOREACH), declare a
40 conditional block (IF/UNLESS/ELSE), include and process another tem‐
41 plate file (INCLUDE) and so on.
42
43 In all other respects, the document is a plain text file and may con‐
44 tain any other content (e.g. HTML, XML, RTF, LaTeX, etc). Directives
45 are inserted in the document within the special markup tags which are
46 '[%' and '%]' by default, but can be changed via the module configura‐
47 tion options. Here's an example of an HTML document with additional
48 Template Toolkit directives.
49
50 [% INCLUDE header
51 title = 'This is an HTML example'
52 %]
53
54 <h1>Some Interesting Links</h1>
55
56 [% webpages = [
57 { url => 'http://foo.org', title => 'The Foo Organisation' }
58 { url => 'http://bar.org', title => 'The Bar Organisation' }
59 ]
60 %]
61
62 Links:
63 <ul>
64 [% FOREACH link = webpages %]
65 <li><a href="[% link.url %]">[% link.title %]</a>
66 [% END %]
67 </ul>
68
69 [% INCLUDE footer %]
70
71 This example shows how the INCLUDE directive is used to load and
72 process separate 'header' and 'footer' template files, including the
73 output in the current document. These files might look like this:
74
75 header:
76
77 <html>
78 <head>
79 <title>[% title %]</title>
80 </head>
81
82 <body bgcolor="#ffffff">
83
84 footer:
85
86 <hr>
87
88 <center>
89 © Copyright 2000 Me, Myself, I
90 </center>
91
92 </body>
93 </html>
94
95 The example also uses the FOREACH directive to iterate through the
96 'webpages' list to build a table of links. In this example, we have
97 defined this list within the template to contain a number of hash ref‐
98 erences, each containing a 'url' and 'title' member. The FOREACH
99 directive iterates through the list, aliasing 'link' to each item (hash
100 ref). The [% link.url %] and [% link.title %] directives then access
101 the individual values in the hash and insert them into the document.
102
103 The following sections show other ways in which data can be defined for
104 use in a template.
105
107 Having created a template file we can now process it to generate some
108 real output. The quickest and easiest way to do this is to use the
109 tpage script. This is provided as part of the Template Toolkit and
110 should be installed in your usual Perl bin directory.
111
112 Assuming you saved your template file as 'mypage.html', you would run
113 the command:
114
115 tpage mypage.html
116
117 This will process the template file, sending the output to STDOUT (i.e.
118 whizzing past you on the screen). You may want to redirect the output
119 to a file but be careful not to specify the same name as the template
120 file, or you'll overwrite it. You may want to use one prefix for your
121 templates such as '.atml' (for 'Another Template Markup Language', per‐
122 haps?) and the regular '.html' for the output files (assuming you're
123 creating HTML, that is). Alternatively, you might redirect the output
124 to another directory. e.g.
125
126 tpage mypage.atml > mypage.html
127 tpage templates/mypage.html > html/mypage.html
128
129 The tpage script is very basic and only really intended to give you an
130 easy way to process a template without having to write any Perl code.
131 A much more flexible tool is ttree, described below, but for now let's
132 look at the output generated by processing the above example (some
133 whitespace removed for brevity):
134
135 <html>
136 <head>
137 <title>This is an HTML example</title>
138 </head>
139
140 <body bgcolor="#ffffff">
141
142 <h1>Some Interesting Links</h1>
143
144 Links:
145 <ul>
146 <li><a href="http://foo.org">The Foo Organsiation</a>
147 <li><a href="http://bar.org">The Bar Organsiation</a>
148 </ul>
149
150 <hr>
151
152 <center>
153 © Copyright 2000 Me, Myself, I
154 </center>
155
156 </body>
157 </html>
158
159 The header and footer template files have been included (assuming you
160 created them and they're in the current directory) and the link data
161 has been built into an HTML list.
162
163 The ttree script, also distributed as part of the Template Toolkit,
164 provides a more flexible way to process template documents. The first
165 time you run the script, it will ask you if it should create a configu‐
166 ration file, usually called '.ttreerc' in your home directory. Answer
167 'y' to have it create the file.
168
169 The ttree documentation describes how you can change the location of
170 this file and also explains the syntax and meaning of the various
171 options in the file. Comments are written to the sample configuration
172 file which should also help.
173
174 perldoc ttree
175 ttree -h
176
177 In brief, the configuration file describes the directories in which
178 template files are to be found (src), where the corresponding output
179 should be written to (dest), and any other directories (lib) that may
180 contain template files that you plan to INCLUDE into your source docu‐
181 ments. You can also specify processing options (such as 'verbose' and
182 'recurse') and provide regular expression to match files that you don't
183 want to process (ignore, accept) or should be copied instead of pro‐
184 cessed (copy).
185
186 An example .ttreerc file is shown here:
187
188 $HOME/.ttreerc:
189 verbose
190 recurse
191
192 # this is where I keep other ttree config files
193 cfg = ~/.ttree
194
195 src = ~/websrc/src
196 lib = ~/websrc/lib
197 dest = ~/public_html/test
198
199 ignore = \b(CVS⎪RCS)\b
200 ignore = ^#
201
202 You can create many different configuration files and store them in the
203 directory specified in the 'cfg' option, shown above. You then add the
204 "-f filename" option to ttree to have it read that file.
205
206 When you run the script, it compares all the files in the 'src' direc‐
207 tory (including those in sub-directories if the 'recurse' option is
208 set), with those in the 'dest' directory. If the destination file
209 doesn't exist or has an earlier modification time than the correspond‐
210 ing source file, then the source will be processed with the output
211 written to the destination file. The "-a" option forces all files to
212 be processed, regardless of modification times.
213
214 The script doesn't process any of the files in the 'lib' directory, but
215 it does add it to the INCLUDE_PATH for the template processor so that
216 it can locate these files via an INCLUDE or PROCESS directive. Thus,
217 the 'lib' directory is an excellent place to keep template elements
218 such as header, footers, etc., that aren't complete documents in their
219 own right.
220
221 You can also specify various Template Toolkit options from the configu‐
222 ration file. Consult the ttree documentation and help summary ("ttree
223 -h") for full details. e.g.
224
225 $HOME/.ttreerc:
226 pre_process = config
227 interpolate
228 post_chomp
229
230 The 'pre_process' option allows you to specify a template file which
231 should be processed before each file. Unsurprisingly, there's also a
232 'post_process' option to add a template after each file. In the frag‐
233 ment above, we have specified that the 'config' template should be used
234 as a prefix template. We can create this file in the 'lib' directory
235 and use it to define some common variables, including those web page
236 links we defined earlier and might want to re-use in other templates.
237 We could also include an HTML header, title, or menu bar in this file
238 which would then be prepended to each and every template file, but for
239 now we'll keep all that in a separate 'header' file.
240
241 $lib/config:
242
243 [% root = '~/abw'
244 home = "$root/index.html"
245 images = "$root/images"
246 email = 'abw@wardley.org'
247 graphics = 1
248 webpages = [
249 { url => 'http://foo.org', title => 'The Foo Organsiation' }
250 { url => 'http://bar.org', title => 'The Bar Organsiation' }
251 ]
252 %]
253
254 Assuming you've created or copied the 'header' and 'footer' files from
255 the earlier example into your 'lib' directory, you can now start to
256 create web pages like the following in your 'src' directory and process
257 them with ttree.
258
259 $src/newpage.html:
260
261 [% INCLUDE header
262 title = 'Another Template Toolkit Test Page'
263 %]
264
265 <a href="[% home %]">Home</a>
266 <a href="mailto:[% email %]">Email</a>
267
268 [% IF graphics %]
269 <img src="[% images %]/logo.gif" align=right width=60 height=40>
270 [% END %]
271
272 [% INCLUDE footer %]
273
274 Here we've shown how pre-defined variables can be used as flags to
275 enable certain feature (e.g. 'graphics') and to specify common items
276 such as an email address and URL's for the home page, images directory
277 and so on. This approach allows you to define these values once so
278 that they're consistent across all pages and can easily be changed to
279 new values.
280
281 When you run ttree, you should see output similar to the following
282 (assuming you have the verbose flag set).
283
284 ttree 1.14 (Template Toolkit version 1.02a)
285
286 Source: /home/abw/websrc/src
287 Destination: /home/abw/public_html/test
288 Include Path: [ /home/abw/websrc/lib ]
289 Ignore: [ \b(CVS⎪RCS)\b, ^# ]
290 Copy: [ ]
291 Accept: [ * ]
292
293 + newpage.html
294
295 The '+' before 'newpage.html' shows that the file was processed, with
296 the output being written to the destination directory. If you run the
297 same command again, you'll see the following line displayed instead
298 showing a '-' and giving a reason why the file wasn't processed.
299
300 - newpage.html (not modified)
301
302 It has detected a 'newpage.html' in the destination directory which is
303 more recent than that in the source directory and so hasn't bothered to
304 waste time re-processing it. To force all files to be processed, use
305 the "-a" option. You can also specify one or more filenames as command
306 line arguments to ttree:
307
308 tpage newpage.html
309
310 This is what the destination page looks like.
311
312 $dest/newpage.html:
313
314 <html>
315 <head>
316 <title>Another Template Toolkit Test Page</title>
317 </head>
318
319 <body bgcolor="#ffffff">
320
321 <a href="~/abw/index.html">Home</a>
322 <a href="mailto:abw@wardley.org">Email me</a>
323
324 <img src="~/abw/images/logo.gif" align=right width=60 height=40>
325
326 <hr>
327
328 <center>
329 © Copyright 2000 Me, Myself, I
330 </center>
331
332 </body>
333 </html>
334
335 You can add as many documents as you like to the 'src' directory and
336 ttree will apply the same process to them all. In this way, it is pos‐
337 sible to build an entire tree of static content for a web site with a
338 single command. The added benefit is that you can be assured of con‐
339 sistency in links, header style, or whatever else you choose to imple‐
340 ment in terms of common templates elements or variables.
341
343 The Template module provides a simple front-end to the Template Toolkit
344 for use in CGI scripts and Apache/mod_perl handlers. Simply 'use' the
345 Template module, create an object instance with the new() method and
346 then call the process() method on the object, passing the name of the
347 template file as a parameter. The second parameter passed is a refer‐
348 ence to a hash array of variables that we want made available to the
349 template:
350
351 #!/usr/bin/perl -w
352
353 use strict;
354 use Template;
355
356 my $file = 'src/greeting.html';
357 my $vars = {
358 message => "Hello World\n"
359 };
360
361 my $template = Template->new();
362
363 $template->process($file, $vars)
364 ⎪⎪ die "Template process failed: ", $template->error(), "\n";
365
366 So that our scripts will work with the same template files as our ear‐
367 lier examples, we'll can add some configuration options to the con‐
368 structor to tell it about our environment:
369
370 my $template->new({
371 # where to find template files
372 INCLUDE_PATH => '/home/abw/websrc/src:/home/abw/websrc/lib',
373 # pre-process lib/config to define any extra values
374 PRE_PROCESS => 'config',
375 });
376
377 Note that here we specify the 'config' file as a PRE_PROCESS option.
378 This means that the templates we process can use the same global vari‐
379 ables defined earlier for our static pages. We don't have to replicate
380 their definitions in this script. However, we can supply additional
381 data and functionality specific to this script via the hash of vari‐
382 ables that we pass to the process() method.
383
384 These entries in this hash may contain simple text or other values,
385 references to lists, others hashes, sub-routines or objects. The Tem‐
386 plate Toolkit will automatically apply the correct procedure to access
387 these different types when you use the variables in a template.
388
389 Here's a more detailed example to look over. Amongst the different
390 template variables we define in $vars, we create a reference to a CGI
391 object and a 'get_user_projects' sub-routine.
392
393 #!/usr/bin/perl -w
394
395 use strict;
396 use Template;
397 use CGI;
398
399 $⎪ = 1;
400 print "Content-type: text/html\n\n";
401
402 my $file = 'userinfo.html';
403 my $vars = {
404 'version' => 3.14,
405 'days' => [ qw( mon tue wed thu fri sat sun ) ],
406 'worklist' => \&get_user_projects,
407 'cgi' => CGI->new(),
408 'me' => {
409 'id' => 'abw',
410 'name' => 'Andy Wardley',
411 },
412 };
413
414 sub get_user_projects {
415 my $user = shift;
416 my @projects = ... # do something to retrieve data
417 return \@projects;
418 }
419
420 my $template = Template->new({
421 INCLUDE_PATH => '/home/abw/websrc/src:/home/abw/websrc/lib',
422 PRE_PROCESS => 'config',
423 });
424
425 $template->process($file, $vars)
426 ⎪⎪ die $template->error();
427
428 Here's a sample template file that we might create to build the output
429 for this script.
430
431 $src/userinfo.html:
432
433 [% INCLUDE header
434 title = 'Template Toolkit CGI Test'
435 %]
436
437 <a href="mailto:[% email %]">Email [% me.name %]</a>
438
439 <p>This is version [% version %]</p>
440
441 <h3>Projects</h3>
442 <ul>
443 [% FOREACH project = worklist(me.id) %]
444 <li> <a href="[% project.url %]">[% project.name %]</a>
445 [% END %]
446 </ul>
447
448 [% INCLUDE footer %]
449
450 This example shows how we've separated the Perl implementation (code)
451 from the presentation (HTML) which not only makes them easier to main‐
452 tain in isolation, but also allows the re-use of existing template ele‐
453 ments such as headers and footers, etc. By using template to create
454 the output of your CGI scripts, you can give them the same consistency
455 as your static pages built via ttree or other means.
456
457 Furthermore, we can modify our script so that it processes any one of a
458 number of different templates based on some condition. A CGI script to
459 maintain a user database, for example, might process one template to
460 provide an empty form for new users, the same form with some default
461 values set for updating an existing user record, a third template for
462 listing all users in the system, and so on. You can use any Perl func‐
463 tionality you care to write to implement the logic of your application
464 and then choose one or other template to generate the desired output
465 for the application state.
466
468 NOTE: the Apache::Template module is now available from CPAN and pro‐
469 vides a simple and easy to use Apache/mod_perl interface to the Tem‐
470 plate Toolkit. It's only in it's first release (0.01) at the time of
471 writing and it currently only offers a fairly basic facility, but it
472 implements most, if not all of what is described below, and it avoids
473 the need to write your own handler. However, in many cases, you'll
474 want to write your own handler to customise processing for your own
475 need, and this section will show you how to get started.
476
477 The Template module can be used in a similar way from an
478 Apache/mod_perl handler. Here's an example of a typical Apache
479 httpd.conf file:
480
481 PerlModule CGI;
482 PerlModule Template
483 PerlModule MyOrg::Apache::User
484
485 PerlSetVar websrc_root /home/abw/websrc
486
487 <Location /user/bin>
488 SetHandler perl-script
489 PerlHandler MyOrg::Apache::User
490 </Location>
491
492 This defines a location called '/user/bin' to which all requests will
493 be forwarded to the handler() method of the MyOrg::Apache::User module.
494 That module might look something like this:
495
496 package MyOrg::Apache::User;
497
498 use strict;
499 use vars qw( $VERSION );
500 use Apache::Constants qw( :common );
501 use Template qw( :template );
502 use CGI;
503
504 $VERSION = 1.59;
505
506 sub handler {
507 my $r = shift;
508
509 my $websrc = $r->dir_config('websrc_root')
510 or return fail($r, SERVER_ERROR,
511 "'websrc_root' not specified");
512
513 my $template = Template->new({
514 INCLUDE_PATH => "$websrc/src/user:$websrc/lib",
515 PRE_PROCESS => 'config',
516 OUTPUT => $r, # direct output to Apache request
517 });
518
519 my $params = {
520 uri => $r->uri,
521 cgi => CGI->new,
522 };
523
524 # use the path_info to determine which template file to process
525 my $file = $r->path_info;
526 $file =~ s[^/][];
527
528 $r->content_type('text/html');
529 $r->send_http_header;
530
531 $template->process($file, $params)
532 ⎪⎪ return fail($r, SERVER_ERROR, $template->error());
533
534 return OK;
535 }
536
537 sub fail {
538 my ($r, $status, $message) = @_;
539 $r->log_reason($message, $r->filename);
540 return $status;
541 }
542
543 The handler accepts the request and uses it to determine the 'web‐
544 src_root' value from the config file. This is then used to define an
545 INCLUDE_PATH for a new Template object. The URI is extracted from the
546 request and a CGI object is created. These are both defined as tem‐
547 plate variables.
548
549 The name of the template file itself is taken from the PATH_INFO ele‐
550 ment of the request. In this case, it would comprise the part of the
551 URL coming after '/user/bin', e.g for '/user/bin/edit', the template
552 file would be 'edit' located in "$websrc/src/user". The headers are
553 sent and the template file is processed. All output is sent directly
554 to the print() method of the Apache request object.
555
557 As we've already shown, it is possible to bind Perl data and functions
558 to template variables when creating dynamic content via a CGI script or
559 Apache/mod_perl process. The Template Toolkit also supports a plugin
560 interface which allows you define such additional data and/or function‐
561 ality in a separate module and then load and use it as required with
562 the USE directive.
563
564 The main benefit to this approach is that you can load the extension
565 into any template document, even those that are processed "statically"
566 by tpage or ttree. You don't need to write a Perl wrapper to explic‐
567 itly load the module and make it available via the stash.
568
569 Let's demonstrate this principle using the DBI plugin written by Simon
570 Matthews <sam@knowledgepool.com>. You can create this template in your
571 'src' directory and process it using ttree to see the results. Of
572 course, this example relies on the existence of the appropriate SQL
573 database but you should be able to adapt it to your own resources, or
574 at least use it as a demonstrative example of what's possible.
575
576 [% INCLUDE header
577 title = 'User Info'
578 %]
579
580 [% USE DBI('dbi:mSQL:mydbname') %]
581
582 <table border=0 width="100%">
583 <tr>
584 <th>User ID</th>
585 <th>Name</th>
586 <th>Email</th>
587 </tr>
588
589 [% FOREACH user = DBI.query('SELECT * FROM user ORDER BY id') %]
590 <tr>
591 <td>[% user.id %]</td>
592 <td>[% user.name %]</td>
593 <td>[% user.email %]</td>
594 </tr>
595 [% END %]
596
597 </table>
598
599 [% INCLUDE footer %]
600
601 A plugin is simply a Perl module in a known location and conforming to
602 a known standard such that the Template Toolkit can find and load it
603 automatically. You can create your own plugin by inheriting from the
604 Template::Plugin module.
605
606 Here's an example which defines some data items ('foo' and 'people')
607 and also an object method ('bar'). We'll call the plugin 'FooBar' for
608 want of a better name and create it in the 'MyOrg::Template::Plug‐
609 in::FooBar' package. We've added a 'MyOrg' to the regular 'Tem‐
610 plate::Plugin::*' package to avoid any conflict with existing plugins.
611
612 You can create a module stub using the Perl utlity h2xs:
613
614 h2xs -A -X -n MyOrg::Template::Plugin::FooBar
615
616 This will create a directory structure representing the package name
617 along with a set of files comprising your new module. You can then
618 edit FooBar.pm to look something like this:
619
620 package MyOrg::Template::Plugin::FooBar;
621
622 use Template::Plugin;
623 use vars qw( $VERSION );
624 use base qw( Template::Plugin );
625
626 $VERSION = 1.23;
627
628 sub new {
629 my ($class, $context, @params) = @_;
630
631 bless {
632 _CONTEXT => $context,
633 foo => 25,
634 people => [ 'tom', 'dick', 'harry' ],
635 }, $class;
636 }
637
638 sub bar {
639 my ($self, @params) = @_;
640 # ...do something...
641 return $some_value;
642 }
643
644 The plugin constructor new() receives the class name as the first
645 parameter, as is usual in Perl, followed by a reference to something
646 called a Template::Context object. You don't need to worry too much
647 about this at the moment, other than to know that it's the main pro‐
648 cessing object for the Template Toolkit. It provides access to the
649 functionality of the processor and some plugins may need to communicate
650 with it. We don't at this stage, but we'll save the reference anyway
651 in the '_CONTEXT' member. The leading underscore is a convention which
652 indicates that this item is private and the Template Toolkit won't
653 attempt to access this member. The other members defined, 'foo' and
654 'people' are regular data items which will be made available to tem‐
655 plates using this plugin. Following the context reference are passed
656 any additional parameters specified with the USE directive, such as the
657 data source parameter, 'dbi:mSQL:mydbname', that we used in the earlier
658 DBI example.
659
660 If you used h2xs to create the module stub then you'll already have a
661 Makefile.PL and you can incite the familiar incantation to build and
662 install it. Don't forget to add some tests to test.pl!
663
664 perl Makefile.PL
665 make
666 make test
667 make install
668
669 If you don't or can't install it to the regular place for your Perl
670 modules (perhaps because you don't have the required privileges) then
671 you can set the PERL5LIB environment variable to specify another loca‐
672 tion. If you're using ttree then you can add the following line to
673 your configuration file instead. This has the effect of add
674 '/path/to/modules' to the @INC array to a similar end.
675
676 $HOME/.ttreerc:
677
678 perl5lib = /path/to/modules
679
680 One further configuration item must be added to inform the toolkit of
681 the new package name we have adopted for our plugins:
682
683 $HOME/.ttreerc:
684
685 plugin_base = 'MyOrg::Template::Plugin'
686
687 If you're writing Perl code to control the Template modules directly,
688 then this value can be passed as a configuration parameter when you
689 create the module.
690
691 use Template;
692
693 my $template = Template->new({
694 PLUGIN_BASE => 'MyOrg::Template::Plugin'
695 });
696
697 Now we can create a template which uses this plugin:
698
699 [% INCLUDE header
700 title = 'FooBar Plugin Test'
701 %]
702
703 [% USE FooBar %]
704
705 Some values available from this plugin:
706 [% FooBar.foo %] [% FooBar.bar %]
707
708 The users defined in the 'people' list:
709 [% FOREACH uid = FooBar.people %]
710 * [% uid %]
711 [% END %]
712
713 [% INCLUDE footer %]
714
715 The 'foo', 'bar' and 'people' items of the FooBar plugin are automati‐
716 cally resolved to the appropriate data items or method calls on the
717 underlying object.
718
719 Using this approach, it is possible to create application functionality
720 in a single module which can then be loaded and used on demand in any
721 template. The simple interface between template directives and plugin
722 objects allows complex, dynamic content to be built from a few simple
723 template documents without knowing anything about the underlying imple‐
724 mentation.
725
727 Andy Wardley <abw@wardley.org>
728
729 <http://wardley.org/⎪http://wardley.org/>
730
732 Template Toolkit version 2.18, released on 09 February 2007.
733
735 Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
736
737 This module is free software; you can redistribute it and/or modify it
738 under the same terms as Perl itself.
739
740
741
742perl v5.8.8 2007-02-09 Template::Tutorial::Web(3)