1 #============================================================= -*-perl-*-
3 # Template::Tutorial::Web
6 # Tutorial on generating web content with the Template Toolkit
9 # Andy Wardley <abw@wardley.org>
12 # Copyright (C) 1996-2008 Andy Wardley. All Rights Reserved.
14 # This module is free software; you can redistribute it and/or
15 # modify it under the same terms as Perl itself.
17 #========================================================================
21 Template::Tutorial::Web - Generating Web Content Using the Template Toolkit
25 This tutorial document provides a introduction to the Template Toolkit and
26 demonstrates some of the typical ways it may be used for generating web
27 content. It covers the generation of static pages from templates using the
28 L<tpage|Template::Tools::tpage> and L<ttree|Template::Tools::ttree> scripts
29 and then goes on to show dynamic content generation using CGI scripts and
30 Apache/mod_perl handlers.
32 Various features of the Template Toolkit are introduced and described briefly
33 and explained by use of example. For further information, see L<Template>,
34 L<Template::Manual> and the various sections within it. e.g
36 perldoc Template # Template.pm module usage
37 perldoc Template::Manual # index to manual
38 perldoc Template::Manual::Config # e.g. configuration options
40 The documentation is also available in HTML format to read online, or download
41 from the Template Toolkit web site:
43 http://template-toolkit.org/docs/
47 The Template Toolkit is a set of Perl modules which collectively
48 implement a template processing system.
50 A template is a text document with special markup tags embedded in it.
51 By default, the Template Toolkit uses 'C<[%>' and 'C<%]>' to denote
52 the start and end of a tag. Here's an example:
56 People of [% planet %], your attention please.
58 This is [% captain %] of the
59 Galactic Hyperspace Planning Council.
61 As you will no doubt be aware, the plans
62 for development of the outlying regions
63 of the Galaxy require the building of a
64 hyperspatial express route through your
65 star system, and regrettably your planet
66 is one of those scheduled for destruction.
68 The process will take slightly less than
75 Tags can contain simple I<variables> (like C<planet> and C<captain>) and more
76 complex I<directives> that start with an upper case keyword (like C<INCLUDE>).
77 A directive is an instruction that tells the template processor to perform
78 some action, like processing another template (C<header> and C<footer> in this
79 example) and inserting the output into the current template. In fact, the
80 simple variables we mentioned are actually C<GET> directives, but the C<GET>
83 People of [% planet %], your attention please. # short form
84 People of [% GET planet %], your attention please. # long form
86 Other directives include C<SET> to set a variable value (the C<SET> keyword is
87 also optional), C<FOREACH> to iterate through a list of values, and C<IF>,
88 C<UNLESS>, C<ELSIF> and C<ELSE> to declare conditional blocks.
90 The Template Toolkit processes all I<text> files equally, regardless of what
91 kind of content they contain. So you can use TT to generate HTML, XML, CSS,
92 Javascript, Perl, RTF, LaTeX, or any other text-based format. In this tutorial,
93 however, we'll be concentrating on generating HTML for web pages.
95 =head1 Generating Static Web Content
97 Here's an example of a template used to generate an HTML document.
100 title = 'This is an HTML example';
103 { url = 'http://foo.org'
104 title = 'The Foo Organisation'
106 { url = 'http://bar.org'
107 title = 'The Bar Organisation'
111 <h1>Some Interesting Links</h1>
113 [% FOREACH page IN pages %]
114 <li><a href="[% page.url %]">[% page.title %]</a>
120 This example shows how the C<INCLUDE> directive is used to load and process
121 separate 'C<header>' and 'C<footer>' template files, including the output in
122 the current document. These files might look something like this:
128 <title>[% title %]</title>
134 <div class="copyright">
135 © Copyright 2007 Arthur Dent
140 The example also uses the C<FOREACH> directive to iterate through the
141 'C<pages>' list to build a table of links. In this example, we have defined
142 this list within the template to contain a number of hash references, each
143 containing a 'C<url>' and 'C<title>' member. The C<FOREACH> directive iterates
144 through the list, aliasing 'C<page>' to each item (in this case, hash array
145 references). The C<[% page.url %]> and C<[% page.title %]> directives then
146 access the individual values in the hash ararys and insert them into the
151 Having created a template file we can now process it to generate some real
152 output. The quickest and easiest way to do this is to use the
153 L<tpage|Template::Tools::tpage> script. This is provided as part of the
154 Template Toolkit and should be installed in your usual Perl bin directory.
156 Assuming you saved your template file as F<example.html>, you would run
161 This will process the template file, sending the output to C<STDOUT> (i.e.
162 whizzing past you on the screen). You may want to redirect the output to a
163 file but be careful not to specify the same name as the template file, or
164 you'll overwrite it. You may want to use one prefix for your templates (e.g.
165 'C<.tt>') and another (e.g. 'C<.html>') for the output files.
167 $ tpage example.tt > example.html
169 Or you can redirect the output to another directory. e.g.
171 $ tpage templates/example.tt > html/example.html
173 The output generated would look like this:
177 <title>This is an HTML example</title>
180 <h1>Some Interesting Links</h1>
182 <li><a href="http://foo.org">The Foo Organsiation</a>
183 <li><a href="http://bar.org">The Bar Organsiation</a>
185 <div class="copyright">
186 © Copyright 2007 Arthur Dent
191 The F<header> and F<footer> template files have been included (assuming
192 you created them and they're in the current directory) and the link data
193 has been built into an HTML list.
197 The L<tpage|Template::Tools::tpage> script gives you a simple and easy way to
198 process a single template without having to write any Perl code. The
199 L<ttree:Template::Tools::ttree> script, also distributed as part of the
200 Template Toolkit, provides a more flexible way to process a number of template
203 The first time you run the script, it will ask you if it should create a
204 configuration file (F<.ttreerc>) in your home directory. Answer C<y> to have
207 The L<ttree:Template::Tools::ttree> documentation describes how you can change
208 the location of this file and also explains the syntax and meaning of the
209 various options in the file. Comments are written to the sample configuration
210 file which should also help.
212 In brief, the configuration file describes the directories in which template
213 files are to be found (C<src>), where the corresponding output should be
214 written to (C<dest>), and any other directories (C<lib>) that may contain
215 template files that you plan to C<INCLUDE> into your source documents. You can
216 also specify processing options (such as C<verbose> and C<recurse>) and provide
217 regular expression to match files that you don't want to process (C<ignore>,
218 C<accept>)> or should be copied instead of being processed as templates (C<copy>).
220 An example F<.ttreerc> file is shown here:
227 # this is where I keep other ttree config files
232 dest = ~/public_html/test
234 ignore = \b(CVS|RCS)\b
237 You can create many different configuration files and store them
238 in the directory specified in the C<cfg> option, shown above. You then
239 add the C<-f filename> option to C<ttree> to have it read that file.
241 When you run the script, it compares all the files in the C<src> directory
242 (including those in sub-directories if the C<recurse> option is set), with
243 those in the C<dest> directory. If the destination file doesn't exist or
244 has an earlier modification time than the corresponding source file, then
245 the source will be processed with the output written to the destination
246 file. The C<-a> option forces all files to be processed, regardless of
249 The script I<doesn't> process any of the files in the C<lib> directory, but it
250 does add it to the C<INCLUDE_PATH> for the template processor so that it can
251 locate these files via an C<INCLUDE>, C<PROCESS> or C<WRAPPER> directive.
252 Thus, the C<lib> directory is an excellent place to keep template elements
253 such as header, footers, etc., that aren't complete documents in their own
256 You can also specify various Template Toolkit options from the configuration
257 file. Consult the L<ttree|Template::Tools::ttree> documentation and help
258 summary (C<ttree -h>) for full details. e.g.
266 The C<pre_process> option allows you to specify a template file which
267 should be processed before each file. Unsurprisingly, there's also a
268 C<post_process> option to add a template after each file. In the
269 fragment above, we have specified that the C<config> template should be
270 used as a prefix template. We can create this file in the C<lib>
271 directory and use it to define some common variables, including those
272 web page links we defined earlier and might want to re-use in other
273 templates. We could also include an HTML header, title, or menu bar
274 in this file which would then be prepended to each and every template
275 file, but for now we'll keep all that in a separate C<header> file.
280 home = "$root/index.html"
281 images = "$root/images"
282 email = 'abw@wardley.org'
285 { url => 'http://foo.org', title => 'The Foo Organsiation' }
286 { url => 'http://bar.org', title => 'The Bar Organsiation' }
290 Assuming you've created or copied the C<header> and C<footer> files from the
291 earlier example into your C<lib> directory, you can now start to create
292 web pages like the following in your C<src> directory and process them
298 title = 'Another Template Toolkit Test Page'
301 <a href="[% home %]">Home</a>
302 <a href="mailto:[% email %]">Email</a>
305 <img src="[% images %]/logo.gif" align=right width=60 height=40>
310 Here we've shown how pre-defined variables can be used as flags to
311 enable certain feature (e.g. C<graphics>) and to specify common items
312 such as an email address and URL's for the home page, images directory
313 and so on. This approach allows you to define these values once so
314 that they're consistent across all pages and can easily be changed to
317 When you run F<ttree>, you should see output similar to the following
318 (assuming you have the verbose flag set).
320 ttree 2.9 (Template Toolkit version 2.20)
322 Source: /home/abw/websrc/src
323 Destination: /home/abw/public_html/test
324 Include Path: [ /home/abw/websrc/lib ]
325 Ignore: [ \b(CVS|RCS)\b, ^# ]
331 The C<+> in front of the C<newpage.html> filename shows that the file was
332 processed, with the output being written to the destination directory. If you
333 run the same command again, you'll see the following line displayed instead
334 showing a C<-> and giving a reason why the file wasn't processed.
336 - newpage.html (not modified)
338 It has detected a C<newpage.html> in the destination directory which is
339 more recent than that in the source directory and so hasn't bothered
340 to waste time re-processing it. To force all files to be processed,
341 use the C<-a> option. You can also specify one or more filenames as
342 command line arguments to C<ttree>:
346 This is what the destination page looks like.
352 <title>Another Template Toolkit Test Page</title>
356 <a href="~/abw/index.html">Home</a>
357 <a href="mailto:abw@wardley.org">Email me</a>
358 <img src="~/abw/images/logo.gif" align=right width=60 height=40>
360 <div class="copyright">
361 © Copyright 2007 Arthur Dent
366 You can add as many documents as you like to the C<src> directory and
367 C<ttree> will apply the same process to them all. In this way, it is
368 possible to build an entire tree of static content for a web site with
369 a single command. The added benefit is that you can be assured of
370 consistency in links, header style, or whatever else you choose to
371 implement in terms of common templates elements or variables.
373 =head1 Dynamic Content Generation Via CGI Script
375 The L<Template> module provides a simple front-end to the Template Toolkit for
376 use in CGI scripts and Apache/mod_perl handlers. Simply C<use> the L<Template>
377 module, create an object instance with the L<new()> method and then call the
378 L<process()> method on the object, passing the name of the template file as a
379 parameter. The second parameter passed is a reference to a hash array of
380 variables that we want made available to the template:
387 my $file = 'src/greeting.html';
389 message => "Hello World\n"
392 my $template = Template->new();
394 $template->process($file, $vars)
395 || die "Template process failed: ", $template->error(), "\n";
397 So that our scripts will work with the same template files as our earlier
398 examples, we'll can add some configuration options to the constructor to
399 tell it about our environment:
402 # where to find template files
403 INCLUDE_PATH => ['/home/abw/websrc/src', '/home/abw/websrc/lib'],
404 # pre-process lib/config to define any extra values
405 PRE_PROCESS => 'config',
408 Note that here we specify the C<config> file as a C<PRE_PROCESS> option.
409 This means that the templates we process can use the same global
410 variables defined earlier for our static pages. We don't have to
411 replicate their definitions in this script. However, we can supply
412 additional data and functionality specific to this script via the hash
413 of variables that we pass to the C<process()> method.
415 These entries in this hash may contain simple text or other values,
416 references to lists, others hashes, sub-routines or objects. The Template
417 Toolkit will automatically apply the correct procedure to access these
418 different types when you use the variables in a template.
420 Here's a more detailed example to look over. Amongst the different
421 template variables we define in C<$vars>, we create a reference to a
422 L<CGI> object and a C<get_user_projects()> sub-routine.
431 print "Content-type: text/html\n\n";
433 my $file = 'userinfo.html';
436 'days' => [ qw( mon tue wed thu fri sat sun ) ],
437 'worklist' => \&get_user_projects,
441 'name' => 'Andy Wardley',
445 sub get_user_projects {
447 my @projects = ... # do something to retrieve data
451 my $template = Template->new({
452 INCLUDE_PATH => '/home/abw/websrc/src:/home/abw/websrc/lib',
453 PRE_PROCESS => 'config',
456 $template->process($file, $vars)
457 || die $template->error();
459 Here's a sample template file that we might create to build the output
465 title = 'Template Toolkit CGI Test'
468 <a href="mailto:[% email %]">Email [% me.name %]</a>
470 <p>This is version [% version %]</p>
474 [% FOREACH project IN worklist(me.id) %]
475 <li> <a href="[% project.url %]">[% project.name %]</a>
481 This example shows how we've separated the Perl implementation (code) from the
482 presentation (HTML). This not only makes them easier to maintain in isolation,
483 but also allows the re-use of existing template elements such as headers and
484 footers, etc. By using template to create the output of your CGI scripts, you
485 can give them the same consistency as your static pages built via
486 L<ttree|Template::Tools::ttree> or other means.
488 Furthermore, we can modify our script so that it processes any one of a
489 number of different templates based on some condition. A CGI script to
490 maintain a user database, for example, might process one template to
491 provide an empty form for new users, the same form with some default
492 values set for updating an existing user record, a third template for
493 listing all users in the system, and so on. You can use any Perl
494 functionality you care to write to implement the logic of your
495 application and then choose one or other template to generate the
496 desired output for the application state.
498 =head1 Dynamic Content Generation Via Apache/Mod_Perl Handler
500 B<NOTE:> the L<Apache::Template> module is available from CPAN and provides a
501 simple and easy to use Apache/mod_perl interface to the Template Toolkit.
502 Although basic, it implements most, if not all of what is described below, and
503 it avoids the need to write your own handler. However, in many cases, you'll
504 want to write your own handler to customise processing for your own need, and
505 this section will show you how to get started.
507 The L<Template> module can be used from an Apache/mod_perl handler. Here's an
508 example of a typical Apache F<httpd.conf> file:
512 PerlModule MyOrg::Apache::User
514 PerlSetVar websrc_root /home/abw/websrc
517 SetHandler perl-script
518 PerlHandler MyOrg::Apache::User
521 This defines a location called C</user/bin> to which all requests will
522 be forwarded to the C<handler()> method of the C<MyOrg::Apache::User>
523 module. That module might look something like this:
525 package MyOrg::Apache::User;
528 use vars qw( $VERSION );
529 use Apache::Constants qw( :common );
530 use Template qw( :template );
538 my $websrc = $r->dir_config('websrc_root')
539 or return fail($r, SERVER_ERROR,
540 "'websrc_root' not specified");
542 my $template = Template->new({
543 INCLUDE_PATH => "$websrc/src/user:$websrc/lib",
544 PRE_PROCESS => 'config',
545 OUTPUT => $r, # direct output to Apache request
553 # use the path_info to determine which template file to process
554 my $file = $r->path_info;
557 $r->content_type('text/html');
558 $r->send_http_header;
560 $template->process($file, $params)
561 || return fail($r, SERVER_ERROR, $template->error());
567 my ($r, $status, $message) = @_;
568 $r->log_reason($message, $r->filename);
572 The handler accepts the request and uses it to determine the C<websrc_root>
573 value from the config file. This is then used to define an C<INCLUDE_PATH>
574 for a new L<Template> object. The URI is extracted from the request and a
575 L<CGI> object is created. These are both defined as template variables.
577 The name of the template file itself is taken from the C<PATH_INFO> element
578 of the request. In this case, it would comprise the part of the URL
579 coming after C</user/bin>, e.g for C</user/bin/edit>, the template file
580 would be C<edit> located in C<$websrc/src/user>. The headers are sent
581 and the template file is processed. All output is sent directly to the
582 C<print()> method of the Apache request object.
584 =head1 Using Plugins to Extend Functionality
586 As we've already shown, it is possible to bind Perl data and functions
587 to template variables when creating dynamic content via a CGI script
588 or Apache/mod_perl process. The Template Toolkit also supports a
589 plugin interface which allows you define such additional data and/or
590 functionality in a separate module and then load and use it as
591 required with the C<USE> directive.
593 The main benefit to this approach is that you can load the extension into
594 any template document, even those that are processed "statically" by
595 C<tpage> or C<ttree>. You I<don't> need to write a Perl wrapper to
596 explicitly load the module and make it available via the stash.
598 Let's demonstrate this principle using the C<DBI> plugin written by Simon
599 Matthews (available from CPAN). You can create this template in your C<src>
600 directory and process it using C<ttree> to see the results. Of course, this
601 example relies on the existence of the appropriate SQL database but you should
602 be able to adapt it to your own resources, or at least use it as a
603 demonstrative example of what's possible.
609 [% USE DBI('dbi:mSQL:mydbname') %]
611 <table border=0 width="100%">
617 [% FOREACH user IN DBI.query('SELECT * FROM user ORDER BY id') %]
619 <td>[% user.id %]</td>
620 <td>[% user.name %]</td>
621 <td>[% user.email %]</td>
628 A plugin is simply a Perl module in a known location and conforming to
629 a known standard such that the Template Toolkit can find and load it
630 automatically. You can create your own plugin by inheriting from the
631 L<Template::Plugin> module.
633 Here's an example which defines some data items (C<foo> and C<people>)
634 and also an object method (C<bar>). We'll call the plugin C<FooBar> for
635 want of a better name and create it in the C<MyOrg::Template::Plugin::FooBar>
636 package. We've added a C<MyOrg> to the regular C<Template::Plugin::*> package
637 to avoid any conflict with existing plugins.
639 package MyOrg::Template::Plugin::FooBar;
640 use base 'Template::Plugin'
644 my ($class, $context, @params) = @_;
647 _CONTEXT => $context,
649 people => [ 'tom', 'dick', 'harry' ],
654 my ($self, @params) = @_;
659 The plugin constructor C<new()> receives the class name as the first
660 parameter, as is usual in Perl, followed by a reference to something called a
661 L<Template::Context> object. You don't need to worry too much about this at
662 the moment, other than to know that it's the main processing object for the
663 Template Toolkit. It provides access to the functionality of the processor and
664 some plugins may need to communicate with it. We don't at this stage, but
665 we'll save the reference anyway in the C<_CONTEXT> member. The leading
666 underscore is a convention which indicates that this item is private and the
667 Template Toolkit won't attempt to access this member. The other members
668 defined, C<foo> and C<people> are regular data items which will be made
669 available to templates using this plugin. Following the context reference are
670 passed any additional parameters specified with the USE directive, such as the
671 data source parameter, C<dbi:mSQL:mydbname>, that we used in the earlier DBI
674 If you don't or can't install it to the regular place for your Perl
675 modules (perhaps because you don't have the required privileges) then
676 you can set the PERL5LIB environment variable to specify another location.
677 If you're using C<ttree> then you can add the following line to your
678 configuration file instead.
682 perl5lib = /path/to/modules
684 One further configuration item must be added to inform the toolkit of
685 the new package name we have adopted for our plugins:
689 plugin_base = 'MyOrg::Template::Plugin'
691 If you're writing Perl code to control the L<Template> modules directly,
692 then this value can be passed as a configuration parameter when you
697 my $template = Template->new({
698 PLUGIN_BASE => 'MyOrg::Template::Plugin'
701 Now we can create a template which uses this plugin:
704 title = 'FooBar Plugin Test'
709 Some values available from this plugin:
710 [% FooBar.foo %] [% FooBar.bar %]
712 The users defined in the 'people' list:
713 [% FOREACH uid = FooBar.people %]
719 The C<foo>, C<bar>, and C<people> items of the FooBar plugin are
720 automatically resolved to the appropriate data items or method calls
721 on the underlying object.
723 Using this approach, it is possible to create application
724 functionality in a single module which can then be loaded and used on
725 demand in any template. The simple interface between template
726 directives and plugin objects allows complex, dynamic content to be
727 built from a few simple template documents without knowing anything
728 about the underlying implementation.
732 Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
736 Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
738 This module is free software; you can redistribute it and/or
739 modify it under the same terms as Perl itself.
745 # perl-indent-level: 4
746 # indent-tabs-mode: nil
749 # vim: expandtab shiftwidth=4: