home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Web.pod < prev    next >
Encoding:
Text File  |  2004-01-30  |  26.8 KB  |  802 lines

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