Header set Expires "Wed, 1 Jan 2000 00:00:00 GMT"
</ifModule>
</filesMatch>
+Options +ExecCGI
RewriteEngine on
DirectoryIndex index.cgi
use File::Basename;
use lib (dirname($0).'/lib');
use Template;
+use Template::Plugin::DBI;
+use DBI;
+use DBD::PgPP;
use CGI;
-use CGI::Carp qw/fatalsToBrowser/;
-#use FindBin qw($Bin $RealBin);
-use Data::Dumper;
-use JSON::PP;
-
my $cgi = new CGI();
my $p=();
for (my $i=0;$i<$absnum;$i++){
$vars->{abspath} .= "../";
}
-
-
+$vars->{dbconn} = 'DBI:PgPP:dbname=handhandlu_db;host=sql629.your-server.de';
+$vars->{dbuser} = 'handhandlu';
+$vars->{dbpass} = 'htUF9jn487fCAJB6';
$vars->{basepath} = $basepath;
$vars->{page} = 'page/'.$page;
$vars->{pagename} = basename($page);
+++ /dev/null
-=head1 CHANGE LOG
-
-=over 4
-
-=item Version 3.030
-
-Make send_by_sendmail set sender like documentation says it does (thanks,
-Michael Schout!)
-
-=item Version 3.029
-
-Allow the MIME-Version header to be replaced (thanks, Florian!)
-
-=item Version 3.028
-
-Various documentation fixes
-
-=item Version 3.027
-
-Add send_to_testfile method (Thanks, AlexanderBecker)
-
-=item Version 3.026
-
-Fix tests to pass with MIME::Types 1.28
-
-=item Version 3.025
-
-Added back support for providing a non-default SMTP port (#21156,
-#48783, thanks John Bokma!).
-
-=item Version 3.024
-
-add git repo link to metadata
-
-=item Version 3.023
-
-Correct erroneous changelog entry
-
-Fix typo in perldoc: utf-8, not utf8
-
-=item Version 3.022
-
-Behave on Cygwin as on Win32 with regard to defaulting to SMTP sending.
-
-Respect crazy people who put multiple Cc or Bcc headers in message (#30574,
-thanks Pavel V. Rochnyack!)
-
-We no longer rewrite array and hash refs in the send_by_sendmail args so
-aggressively.
-
-Cope with missing local sendmail (thanks to Debian for patching for this, and
-for putting up with me (rjbs) being an insufferable jerk!)
-
-Fix weird unicode-in-$1 bug (thanks SREZIC!)
-
-Other minor bug fixes.
-
-=item Version 3.021
-
-Replace Email::Date with Email::Date::Format to limit prereqs
-(Email::Date::Format produced just for this!)
-
-Begin the process of removing use of ExtUtils::TBone for testing
-
-=item Version 3.020
-
-Optimized code for speedup of creation of two-part messages. The internal
-structure of the object has changes, but that won't matter if you were
-using the published interface. (Sam Tregar)
-
-Removed the "advanced features", ie auto-fallback delivery, from
-send_by_smtp. They didn't belong there in the first place.
-
-=item Version 3.01_06 (2007/07/29)
-
-First release from Perl Email Project. Updated packaging.
-
-=item Version 3.01_04 (2004/05/05)
-
-Reworked the new send_by_smtp stuff. Documentation modifications.
-
-=item Version 3.01_02 (2003/08/28)
-
-Well, it seems 3.01_01 failed tests on Win32 due to me accidentally
-changing the line ending format to DOSish. Also the way that email
-extraction for SMTP with or without Mail::Address was different (from
-2.117 even). So ive fixed that.
-
-Anybody depending on the undocumented extract_addrs() is in for a suprise.
-I suggest you look at using Mail::Address.
-
-=item Version 3.01_01 (2003/04/25 - 2003/08/21)
-
-(This version is a test release, if its ok then I'll re-release it as
-3.02)
-
-Patched the pod to use correct entities Thanks to Ed Avis for the patch.
-Added better support for funky names in the from field when sending via SMTP, thanks to
-prodding by Darren Hemphill and Ollie Gallardo. (Actually I kind of messed this up orginally
-and no doubt Darren wasn't impressed. I ended up using something pretty close to his solution.
-My bad for not paying more attention. Sorry mate.)
-
-08/21: Apparently I never uploaded my changes for this version to CPAN. Sigh.
-
-*** Win32 CHANGES ***
-
-Up until this release the default send() method for all OS'es has been to invoke sendmail
-and pipe the mail to it. This behaviour has now changed on Win32 to default to using SMTP.
-This means that if your /site/lib/Net/libnet.cfg file is properly configured then you can
-use SMTP without specifying a send method explicitly. This seemed a rational decision as
-most Win32 users who send mails are using an SMTP server and not a tool like sendmail.
-
-*** SMTP CHANGES ***
-
-Jonathan Eunice <jeunice at illuminata dot com> pointed out an interesting bug in the
-interaction between MIME::Lite and Net::SMTP/Net::CMD. This was that sending a mail
-ending in "\n\n" without additional encoding would cause Net::CMD to send an incorrect
-end of mail signal to the SMTP server which would result in A) The mail failing to be sent due
-to a timeout, and B) MIME::Lite to report that all was well.
-
-This has been fixed by checking to make sure that if the last character sent was \n, but the
-last two chars were not \r\n then the \n is turned into an \r, which Net::CMD then adds an \n
-to and then sends the normal ".\r\n" to terminate the message. Weird error, that im not
-entirely sure has been resolved properly. Please inform me if this screws anything up that it
-shouldn't.
-
-As stated earlier send_by_smtp wasnt extracting the _real_ email address from the overall fancy
-once specified in the From: field. This is resolved now, fancy display names are now possible
-while using SMTP.
-
-*** Content-Id ***
-
-It was pointed out by alex via CPAN RT that Content-Id needs to have angle brackets around
-it or HTML mails dont show up properly in many mail clients, furthermore the RFC mandates it
-(to be honest im taking his word on this, please feel free to yell at me if this causes trouble),
-so as he suggested I am automatically adding them in they arent provided.
-
-*** sendmail path ***
-
-Dom pointed out via CPAN RT that despite some effort going in to trying to discover the correct
-location of sendmail, that it was still using a bad default. Fixed.
-
-*** Date Stamping ***
-
-Kurt reported via RT that datestamps were not being correctly formatted. His patch has been incorporated
-with only one change, a comment where Perl was spelled PERL :-)
-
-*** Quoted printable fix ***
-
-Klaus Rusch noted a bug in how quoted-printable handled weird \r\n combinations. Fixed now.
-
-=item Version 3.01 (2003/04/25)
-
-Eryq has reappeared long enough to graciously hand over the maintaince of the
-module to me. Thanks.
-
-=item Version 3.00 (2003/04/24)
-
-Eryq has disappeared. His web site remains but he doesnt answer emails.
-
-I have taken it onto myself to take over maintenance until he returns to
-reclaim his excellent work.
-
-I don't intend to develop this in an serious way. I'll patch it if people
-have a patch and generally keep it ticking over, but dont expect new features.
-
-This release has code that actually works with MIME::Lite now. As well as a few
-other minor additions (like a test for this functionailty)
-
-For stuff that could be done, a first place would be to rewrite and extend the
-test suite. It should use Test::More or Test::Builder at the very least.
-
-I also might rip out the preformatted doc pages. It makes the distro way fatter
-than it needs to be. I reckon the package contains the POD in at least three forms.
-A wee tad overkill I think. :-)
-
-=item Version 2.117 (2001/08/20)
-
-The terms-of-use have been placed in the distribution file "COPYING".
-Also, small documentation tweaks were made.
-
-
-=item Version 2.116 (2001/08/17)
-
-Added long-overdue patch which makes the instance method form
-of send() do the right thing when given HOW... arguments.
-I<Thanks to Casey West for the patch.>
-
-=item Version 2.114 (2001/08/16)
-
-New special 'AUTO' content type in new()/build() tells MIME::Lite to
-try and guess the type from file extension. To make use of
-this, you'll want to install B<MIME::Types>.
-The "AUTO" setting can be made the default default (instead of "TEXT")
-if you set C<$AUTO_CONTENT_TYPE = 1, $PARANOID = 0>.
-I<Thanks to> Ville SkyttE<228> I<for these patches.>
-
-File::Basename is used if it is available.
-I<Thanks to> Ville SkyttE<228> I<for this patch.>
-
-SMTP failures (in send_by_smtp) now add the $smtp-E<gt>message to the
-croak'ed exception, so if things go wrong, you get a better
-idea of what and why.
-I<Thanks to Thomas R. Wyant III for the patch.>
-
-Made a subtle change to C<as_string> which supposedly fixes a
-failed MIME data.t test with Perl 5.004_04 on NT 4 sp6.
-The problem might only exist in this old perl, but as the patch
-author says, not everyone has climbed higher on the Perl ladder.
-I<Thanks to John Gotts for the patch.>
-
-Added C<contrib> directory, with F<MailTool.pm>.
-I<Thanks to Tom Wyant for this contribution.>
-
-Improved HTML documentation (notice the links to
-the individual methods in the top menu).
-
-Corrected some mis-docs.
-
-
-=item Version 2.111 (2001/04/03)
-
-Added long-overdue C<parts()> and C<parts_DFS()> methods.
-
- No instance method
- For accessing the subparts?
- That can't be right. D'OH!
-
-Added long-overdue auto-verify logic to C<print()> method.
-
-Added long-overdue C<preamble()> method for getting/setting
-the preamble text.
-I<Thanks to Jim Daigle for inspiring this.>
-
-
-=item Version 2.108 (2001/03/30)
-
-New C<field_order()> allows you to set the header order, both on a
-per-message basis, and package-wide.
-I<Thanks to Thomas Stromberg for suggesting this.>
-
-Added code to try and divine "sendmail" path more intelligently.
-I<Thanks to Slaven Rezic for the suggestion.>
-
-
-=item Version 2.107 (2001/03/27)
-
-Fixed serious bug where tainted data with quoted-printable encoding
-was causing infinite loops. The "fix" untaints the data in question,
-which is not optimal, but it's probably benign in this case.
-I<Thanks to Stefan Sautter for tracking this nasty little beast down.>
-I<Thanks to Larry Geralds for a related patch.>
-
- "Doctor, O doctor:
- it's painful when I do *this* --"
- "Simple: don't *do* that."
-
-Fixed bugs where a non-local C<$_> was being modified... again!
-Will I never learn?
-I<Thanks to Maarten Koskamp for reporting this.>
-
- Dollar-underscore
- can poison distant waters;
- 'local' must it be.
-
-Fixed buglet in C<add()> where all value references were being treated
-as arrayrefs, instead of as possibly-self-stringifying object refs.
-Now you can send in an object ref as the 2nd argument.
-I<Thanks to dLux for the bug report.>
-
- That ref is a string?
- Operator overload
- has ruined my day.
-
-Added "Approved" as an acceptable header field for C<new()>, as per RFC1036.
-I<Thanks to Thomax for the suggestion regarding MIME-tools.>
-
-Small improvements to docs to make different uses of attach()
-and various arguments clearer.
-I<Thanks to Sven Rassman and Roland Walter for the suggestions.>
-
-
-=item Version 2.106 (2000/11/21)
-
-Added Alpha version of scrub() to make it easy for people to suppress
-the printing of unwanted MIME attributes (like Content-length).
-I<Thanks to the many people who asked for this.>
-
-Headers with empty-strings for their values are no longer
-printed. This seems sensible, and helps us implement scrub().
-
-
-=item Version 2.105 (2000/10/14)
-
-The regression-test failure was identified, and it was my fault.
-Apparently some of the \-quoting in my "autoloaded" code was
-making Perl 5.6 unhappy. For this nesting-related idiocy,
-a nesting kaiku.
-I<Thanks to Scott Schwartz for identifying the problem.>
-
- In a pattern, my
- backslash-s dwells peacefully,
- unambiguous --
-
- but I embed it
- in a double-quoted string
- doubling the backslash --
-
- interpolating
- that same double-quoted string
- in other patterns --
-
- and, worlds within worlds,
- I single-quote the function
- to autoload it --
-
- changing the meaning
- of the backslash and the 's';
- and Five-Point-Six growls.
-
-
-=item Version 2.104 (2000/09/28)
-
-Now attempts to load and use Mail::Address for parsing email
-addresses I<before> falling back to our own method.
-I<Thanks to numerous people for suggesting this.>
-
- Parsing addresses
- is too damn hard. One last hope:
- Let Graham Barr do it!
-
-For the curious, the version of Mail::Address appears
-as the "A" number in the X-Mailer:
-
- X-Mailer: MIME::Lite 2.104 (A1.15; B2.09; Q2.03)
-
-Added B<FromSender> option to send_by_sendmail().
-I<Thanks to Bill Moseley for suggesting this feature.>
-
-
-=item Version 2.101 (2000/06/06)
-
-Major revision to print_body() and body_as_string() so that
-"body" really means "the part after the header", which is what most
-people would want in this context. This is B<not> how it was used
-1.x, where "body" only meant "the body of a simple singlepart".
-Hopefully, this change will solve many problems and create very few ones.
-
-Added support for attaching a part to a "message/rfc822", treating
-the "message" type as a multipart-like container.
-
-Now takes care not to include "Bcc:" in header when using send_by_smtp,
-as a safety precaution against qmail's behavior.
-I<Thanks to Tatsuhiko Miyagawa for identifying this problem.>
-
-Improved efficiency of many stringifying operations by using
-string-arrays which are joined, instead of doing multiple appends
-to a scalar.
-
-Cleaned up the "examples" directory.
-
-
-=item Version 1.147 (2000/06/02)
-
-Fixed buglet where lack of Cc:/Bcc: was causing extract_addrs
-to emit "undefined variable" warnings. Also, lack of a "To:" field
-now causes a croak.
-I<Thanks to David Mitchell for the bug report and suggested patch.>
-
-
-=item Version 1.146 (2000/05/18)
-
-Fixed bug in parsing of addresses; please read the WARNINGS section
-which describes recommended address formats for "To:", "Cc:", etc.
-Also added automatic inclusion of a UT "Date:" at top level unless
-explicitly told not to.
-I<Thanks to Andy Jacobs for the bug report and the suggestion.>
-
-=item Version 1.145 (2000/05/06)
-
-Fixed bug in encode_7bit(): a lingering C</e> modifier was removed.
-I<Thanks to Michael A. Chase for the patch.>
-
-
-=item Version 1.142 (2000/05/02)
-
-Added new, taint-safe invocation of "sendmail", one which also
-sets up the C<-f> option. Unfortunately, I couldn't make this automatic:
-the change could have broken a lot of code out there which used
-send_by_sendmail() with unusual "sendmail" variants.
-So you'll have to configure "send" to use the new mechanism:
-
- MIME::Lite->send('sendmail'); ### no args!
-
-I<Thanks to Jeremy Howard for suggesting these features.>
-
-
-=item Version 1.140 (2000/04/27)
-
-Fixed bug in support for "To", "Cc", and "Bcc" in send_by_smtp():
-multiple (comma-separated) addresses should now work fine.
-We try real hard to extract addresses from the flat text strings.
-I<Thanks to John Mason for motivating this change.>
-
-Added automatic verification that attached data files exist,
-done immediately before the "send" action is invoked.
-To turn this off, set $MIME::Lite::AUTO_VERIFY to false.
-
-=item Version 1.137 (2000/03/22)
-
-Added support for "Cc" and "Bcc" in send_by_smtp().
-To turn this off, set $MIME::Lite::AUTO_CC to false.
-I<Thanks to Lucas Maneos for the patch, and tons of others for
-the suggestion.>
-
-Chooses a better default content-transfer-encoding if the content-type
-is "image/*", "audio/*", etc.
-To turn this off, set $MIME::Lite::AUTO_ENCODE to false.
-I<Thanks to many folks for the suggestion.>
-
-Fixed bug in QP-encoding where a non-local C<$_> was being modified.
-I<Thanks to Jochen Stenzel for finding this very obscure bug!>
-
-Removed references to C<$`>, C<$'>, and C<$&> (bad variables
-which slow things down).
-
-Added an example of how to send HTML files with enclosed in-line
-images, per popular demand.
-
-
-=item Version 1.133 (1999/04/17)
-
-Fixed bug in "Data" handling: arrayrefs were not being handled
-properly.
-
-
-=item Version 1.130 (1998/12/14)
-
-Added much larger and more-flexible send() facility.
-I<Thanks to Andrew McRae (and Optimation New Zealand Ltd)
-for the Net::SMTP interface. Additional thanks to the many folks
-who requested this feature.>
-
-Added get() method for extracting basic attributes.
-
-New... "t" tests!
-
-
-=item Version 1.124 (1998/11/13)
-
-Folded in filehandle (FH) support in build/attach.
-I<Thanks to Miko O'Sullivan for the code.>
-
-
-=item Version 1.122 (1998/01/19)
-
-MIME::Base64 and MIME::QuotedPrint are used if available.
-
-The 7bit encoding no longer does "escapes"; it merely strips 8-bit characters.
-
-
-=item Version 1.121 (1997/04/08)
-
-Filename attribute is now no longer ignored by build().
-I<Thanks to Ian Smith for finding and patching this bug.>
-
-
-=item Version 1.120 (1997/03/29)
-
-Efficiency hack to speed up MIME::Lite::IO_Scalar.
-I<Thanks to David Aspinwall for the patch.>
-
-
-=item Version 1.116 (1997/03/19)
-
-Small bug in our private copy of encode_base64() was patched.
-I<Thanks to Andreas Koenig for pointing this out.>
-
-New, prettier way of specifying mail message headers in C<build()>.
-
-New quiet method to turn off warnings.
-
-Changed "stringify" methods to more-standard "as_string" methods.
-
-
-=item Version 1.112 (1997/03/06)
-
-Added C<read_now()>, and C<binmode()> method for our non-Unix-using brethren:
-file data is now read using binmode() if appropriate.
-I<Thanks to Xiangzhou Wang for pointing out this bug.>
-
-
-=item Version 1.110 (1997/03/06)
-
-Fixed bug in opening the data filehandle.
-
-
-=item Version 1.102 (1997/03/01)
-
-Initial release.
-
-
-=item Version 1.101 (1997/03/01)
-
-Baseline code.
-Originally created: 11 December 1996. Ho ho ho.
-
-=back
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::FAQ
-#
-# DESCRIPTION
-
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#========================================================================
-
-=head1 NAME
-
-Template::FAQ - Frequently Asked Questions about the Template Toolkit
-
-=head1 Template Toolkit Language
-
-=head2 Why doesn't [% a = b IF c %] work as expected?
-
-There's a limitation in the TT2 parser which means that the following code
-doesn't work as you might expect:
-
- [% a = b IF c %]
-
-The parser interprets it as an attempt to set C<a> to the result of
-C<b IF c>, like this:
-
- [% a = (b IF c) %]
-
-If you want to set C<a = b> only if C<c> is true, then do this instead:
-
- [% SET a = b IF c %]
-
-The explicit C<SET> keyword gives the parser the clue it needs to do the
-right thing.
-
-NOTE: this will be fixed in TT3
-
-=head2 If I'm using TT to write out a TT template, is there a good way to escape [% and %]?
-
-You can do something like this:
-
- [% stag = "[\%"
- etag = "%\]"
- %]
-
-and then:
-
- [% stag; 'hello'; etag %]
-
-Or you can use the C<TAGS> directive, like so:
-
- [% TAGS [- -] %]
- [- INCLUDE foo -] # is a directive
- [% INCLUDE foo %] # not a directive
-
-=head2 How do I iterate over a hash?
-
-This is covered in the L<Template::Manual::VMethods> section of the
-manual. A list of all the keys that are in the hash can be obtained with the
-C<keys> virtual method. You can then iterate over that list and by looking up
-each key in turn get the value.
-
- [% FOREACH key = product.keys %]
- [% key %] => [% product.$key %]
- [% END %]
-
-=head1 Plugins
-
-=head2 How do I get the Table plugin to order data across rather than down?
-
-Order the data into rows:
-
- Steve Karen Jeff
- Brooklyn Nantucket Fairfax
- NY MA VA
-
- [% USE table(data, rows=3) %]
-
-Then ask for each column
-
- [% FOREACH column = table.cols %]
-
-And then print each item in the column going across the output rows
-
- [% FOREACH item = column %]
- <td>[% item %]</td>
- [% END %]
-
-=head2 Accessing Cookies
-
-Jeff Boes E<lt>jboes@nexcerpt.comE<gt> asks:
-
- Does anyone have a quick-n-dirty approach to accessing
- cookies from templates?
-
-Jonas Liljegren answers:
-
- [% USE CGI %]
-
- <p>The value is [% CGI.cookie('cookie_name') | html %]
-
-
-=head1 Extending the Template Toolkit
-
-=head2 Can I serve templates from a database?
-
-Short answer: yes, Chris Nandor has done this for Slash. You need to
-subclass L<Template::Provider>. See the mailing list archives for further
-info.
-
-=head2 Can I fetch templates via http?
-
-To do the job properly, you should subclass L<Template::Provider> to
-C<Template::Provider::HTTP> and use a C<PREFIX_MAP> option to bind the C<http>
-template prefix to that particular provider (you may want to go digging around
-in the F<Changes> file around version 2.01 for more info on C<PREFIX_MAP> - it
-may not be properly documented anywhere else...yet!). e.g.
-
- use Template::Provider::HTTP;
-
- my $file = Template::Provider( INCLUDE_PATH => [...] );
- my $http = Template::Provider::HTTP->new(...);
- my $tt2 = Template->new({
- LOAD_TEMPLATES => [ $file, $http ],
- PREFIX_MAP => {
- file => '0', # file:foo.html
- http => '1', # http:foo.html
- default => '0', # foo.html => file:foo.html
- }
- });
-
-Now a template specified as:
-
- [% INCLUDE foo %]
-
-will be served by the 'file' provider (the default). Otherwise you
-can explicitly add a prefix:
-
- [% INCLUDE file:foo.html %]
- [% INCLUDE http:foo.html %]
- [% INCLUDE http://www.xyz.com/tt2/header.tt2 %]
-
-This same principal can be used to create a DBI template provider. e.g.
-
- [% INCLUDE dbi:foo.html %]
-
-Alas, we don't yet have a DBI provider as part of the Template Toolkit. There
-has been some talk on the mailing list about efforts to develop DBI and/or
-HTTP providers but as yet no-one has stepped forward to take up the
-challenge...
-
-In the mean time, Craig Barrat's post from the mailing list has some useful
-pointers on how to achieve this using existing modules. See
-L<http://tt2.org/pipermail/templates/2001-May/000954.html>
-
-=head1 Miscellaneous
-
-=head2 How can I find out the name of the main template being processed?
-
-The C<template> variable contains a reference to the
-Template::Document object for the main template you're processing
-(i.e. the one provided as the first argument to the Template process()
-method). The C<name> method returns its name.
-
- [% template.name %] # e.g. index.html
-
-=head2 How can I find out the name of the current template being processed?
-
-The C<template> variable always references the I<main> template being processed.
-So even if you call [% INCLUDE header %], and that calls [% INCLUDE menu %],
-the C<template> variable will be unchanged.
-
-index.html:
-
- [% template.name %] # index.html
- [% INCLUDE header %]
-
-header:
-
- [% template.name %] # index.html
- [% INCLUDE menu %]
-
-menu:
-
- [% template.name %] # index.html
-
-In contrast, the C<component> variable always references the I<current>
-template being processed.
-
-index.html
-
- [% component.name %] # index.html
- [% INCLUDE header %]
-
-header:
-
- [% component.name %] # header
- [% INCLUDE menu %]
-
-menu:
-
- [% component.name %] # menu
-
-=head2 How do I print the modification time of the template or component?
-
-The C<template> and C<component> variables reference the main template
-and the current template being processed (see previous questions).
-The C<modtime> method returns the modification time of the
-corresponding template file as a number of seconds since the Unix
-epoch (00:00:00 GMT 1st January 1970).
-
-This number doesn't mean much to anyone (except perhaps serious Unix
-geeks) so you'll probably want to use the Date plugin to format it for
-human consumption.
-
- [% USE Date %]
- [% template.name %] last modified [% Date.format(template.modtime) %]
-
-=head2 How can I configure variables on a per-request basis?
-
-One easy way to achieve this is to define a single C<PRE_PROCESS> template
-which loads in other configuration files based on variables defined or other
-conditions.
-
-For example, my setup usually looks something like this:
-
- PRE_PROCESS => 'config/main'
-
-config/main:
-
- [% DEFAULT style = 'text'
- section = template.section or 'home';
-
- PROCESS config/site
- + config/urls
- + config/macros
- + "config/style/$style"
- + "config/section/$section"
- + ...
- %]
-
-This allows me to set a single 'style' variable to control which config
-file gets pre-processed to set my various style options (colours, img paths,
-etc). For example:
-
-config/style/basic:
-
- [% style = {
- name = style # save existing 'style' var as 'style.name'
-
- # define various other style variables....
- col = {
- back => '#ffffff'
- text => '#000000'
- # ...etc...
- }
-
- logo = {
- # ...etc...
- }
-
- # ...etc...
- }
- %]
-
-Each source template can declare which section it's in via a META
-directive:
-
- [% META
- title = 'General Information'
- section = 'info'
- %]
- ...
-
-This controls which section configuration file gets loaded to set various
-other variables for defining the section title, menu, etc.
-
-config/section/info:
-
- [% section = {
- name = section # save 'section' var as 'section.name'
- title = 'Information'
- menu = [ ... ]
- # ...etc...
- }
- %]
-
-This illustrates the basic principal but you can extend it to perform
-pretty much any kind of per-document initialisation that you require.
-
-=head2 Why do I get rubbish for my utf-8 templates?
-
-First of all, make sure that your template files define a Byte Order
-Mark L<http://en.wikipedia.org/wiki/Byte_Order_Mark>
-
-If you for some reason don't want to add BOM to your templates, you can
-force Template to use a particular encoding (e.g. C<utf8>) for your
-templates with the C<ENCODING> option.
-
- my $template = Template->new({
- ENCODING => 'utf8'
- });
-
-=head1 Questions About This FAQ
-
-=head2 Why is this FAQ so short?
-
-Because we don't have anyone maintaining it.
-
-=head2 Can I help?
-
-Yes please :-)
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual
-#
-# DESCRIPTION
-# Front-page for the TT manual.
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual - Template Toolkit User Manual
-
-=head1 Template Toolkit Manual
-
-The Template Toolkit manual contains documentation on using and extending
-the Template Toolkit.
-
-=head2 Template::Manual::Intro
-
-The L<Template::Manual::Intro> page provides an introduction to the Template Toolkit
-
-=head2 Template::Manual::Syntax
-
-The L<Template::Manual::Syntax> describes the syntax and structure of
-templates and the directive tags embedded within them.
-
-=head2 Template::Manual::Directives
-
-The L<Template::Manual::Directives> page lists all the Template Toolkit
-directives and gives examples of their use.
-
-=head2 Template::Manual::Variables
-
-The L<Template::Manual::Variables> page describes the use of variables
-in templates.
-
-=head2 Template::Manual::VMethods
-
-The L<Template::Manual::VMethods> page provides a full list of virtual
-methods that can be used in conjunction with variables, and gives examples
-of their use.
-
-=head2 Template::Manual::Config
-
-The L<Template::Manual::Config> page describes all of the Template Toolkit
-configuration options.
-
-=head2 Template::Manual::Filters
-
-The L<Template::Manual::Filters> page lists all of the Template Toolkit
-filters and gives examples of their use.
-
-=head2 Template::Manual::Plugins
-
-The L<Template::Manual::Plugins> page lists all of the standard plugins
-distributed with Template Toolkit and gives examples of their use.
-
-=head2 Template::Manual::Internals
-
-The L<Template::Manual::Internals> page describes the internal workings of the
-Template Toolkit. It is aimed at developers who wish to extend or modify the
-
-=head2 Template::Manual::Views
-
-The L<Template::Manual::Views> page describes the experimental C<VIEW>
-directive.
-
-=head2 Template::Manual::Credits
-
-The L<Template::Manual::Credits> page lists the people who have contributed to
-the Template Toolkit.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Config
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2014 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Config - Configuration options
-
-=head1 Template Style and Parsing Options
-
-=head2 ENCODING
-
-The C<ENCODING> option specifies the template files' character encoding:
-
- my $template = Template->new({
- ENCODING => 'utf8',
- });
-
-A template which starts with a Unicode byte order mark (BOM) will have its
-encoding detected automatically.
-
-=head2 START_TAG, END_TAG
-
-The C<START_TAG> and C<END_TAG> options are used to specify character
-sequences or regular expressions that mark the start and end of inline
-template directives. The default values for C<START_TAG> and C<END_TAG> are
-'C<[%>' and 'C<%]>' respectively, giving us the familiar directive style:
-
- [% example %]
-
-Any Perl regex characters can be used and therefore should be escaped
-(or use the Perl C<quotemeta> function) if they are intended to
-represent literal characters.
-
- my $template = Template->new({
- START_TAG => quotemeta('<+'),
- END_TAG => quotemeta('+>'),
- });
-
-Example:
-
- <+ INCLUDE foobar +>
-
-The C<TAGS> directive can also be used to set the C<START_TAG> and C<END_TAG> values
-on a per-template file basis.
-
- [% TAGS <+ +> %]
-
-=head2 OUTLINE_TAG
-
-The C<OUTLINE_TAG> option can be used to enable single-line "outline" directives.
-
- my $template = Template->new({
- OUTLINE_TAG => '%%',
- });
-
-This allows you to use both inline and outline tags like so:
-
- %% IF user
- Hello [% user.name %]
- %% END
-
-The C<OUTLINE_TAG> string (or regex) must appear at the start of a line. The
-directive continues until the end of the line. The newline character at the
-end of the line is considered to be the invisible end-of-directive marker and
-is removed.
-
-=head2 TAG_STYLE
-
-The C<TAG_STYLE> option can be used to set both C<START_TAG> and C<END_TAG>
-according to pre-defined tag styles.
-
- my $template = Template->new({
- TAG_STYLE => 'star',
- });
-
-Available styles are:
-
- template [% ... %] (default)
- template1 [% ... %] or %% ... %% (TT version 1)
- metatext %% ... %% (Text::MetaText)
- star [* ... *] (TT alternate)
- php <? ... ?> (PHP)
- asp <% ... %> (ASP)
- mason <% ... > (HTML::Mason)
- html <!-- ... --> (HTML comments)
-
-The C<outline> style uses the default markers for C<START_TAG> and C<END_TAG>
-(C<[%> and C<%]> respectively) and additionally defines C<OUTLINE_TAG> to
-be C<%%>.
-
- my $template = Template->new({
- TAG_STYLE => 'outline',
- });
-
-This allows you to use both inline and outline tags like so:
-
- %% IF user
- Hello [% user.name %]
- %% END
-
-Any values specified for C<START_TAG>, C<END_TAG> and/or C<OUTLINE_TAG>
-will override those defined by a C<TAG_STYLE>.
-
-The C<TAGS> directive may also be used to set a C<TAG_STYLE>
-
- [% TAGS html %]
- <!-- INCLUDE header -->
-
-=head2 PRE_CHOMP, POST_CHOMP
-
-Anything outside a directive tag is considered plain text and is
-generally passed through unaltered (but see the L<INTERPOLATE> option).
-This includes all whitespace and newlines characters surrounding
-directive tags. Directives that don't generate any output will leave
-gaps in the output document.
-
-Example:
-
- Foo
- [% a = 10 %]
- Bar
-
-Output:
-
- Foo
-
- Bar
-
-The C<PRE_CHOMP> and C<POST_CHOMP> options can help to clean up some of this
-extraneous whitespace. Both are disabled by default.
-
- my $template = Template-E<gt>new({
- PRE_CHOMP => 1,
- POST_CHOMP => 1,
- });
-
-With C<PRE_CHOMP> set to C<1>, the newline and whitespace preceding a directive
-at the start of a line will be deleted. This has the effect of
-concatenating a line that starts with a directive onto the end of the
-previous line.
-
- Foo <----------.
- |
- ,---(PRE_CHOMP)----'
- |
- `-- [% a = 10 %] --.
- |
- ,---(POST_CHOMP)---'
- |
- `-> Bar
-
-With C<POST_CHOMP> set to C<1>, any whitespace after a directive up to and
-including the newline will be deleted. This has the effect of joining
-a line that ends with a directive onto the start of the next line.
-
-If C<PRE_CHOMP> or C<POST_CHOMP> is set to C<2>, all whitespace including any
-number of newline will be removed and replaced with a single space.
-This is useful for HTML, where (usually) a contiguous block of
-whitespace is rendered the same as a single space.
-
-With C<PRE_CHOMP> or C<POST_CHOMP> set to C<3>, all adjacent whitespace
-(including newlines) will be removed entirely.
-
-These values are defined as C<CHOMP_NONE>, C<CHOMP_ONE>, C<CHOMP_COLLAPSE> and
-C<CHOMP_GREEDY> constants in the L<Template::Constants> module. C<CHOMP_ALL>
-is also defined as an alias for C<CHOMP_ONE> to provide backwards
-compatibility with earlier version of the Template Toolkit.
-
-Additionally the chomp tag modifiers listed below may also be used for
-the C<PRE_CHOMP> and C<POST_CHOMP> configuration.
-
- my $template = Template->new({
- PRE_CHOMP => '~',
- POST_CHOMP => '-',
- });
-
-C<PRE_CHOMP> and C<POST_CHOMP> can be activated for individual directives by
-placing a 'C<->' immediately at the start and/or end of the directive.
-
- [% FOREACH user IN userlist %]
- [%- user -%]
- [% END %]
-
-This has the same effect as C<CHOMP_ONE> in removing all whitespace
-before or after the directive up to and including the newline. The
-template will be processed as if written:
-
- [% FOREACH user IN userlist %][% user %][% END %]
-
-To remove all whitespace including any number of newlines, use the 'C<~>'
-character instead.
-
- [% FOREACH user IN userlist %]
-
- [%~ user ~%]
-
- [% END %]
-
-To collapse all whitespace to a single space, use the 'C<=>' character.
-
- [% FOREACH user IN userlist %]
-
- [%= user =%]
-
- [% END %]
-
-Here the template is processed as if written:
-
- [% FOREACH user IN userlist %] [% user %] [% END %]
-
-If you have C<PRE_CHOMP> or C<POST_CHOMP> set as configuration options then
-you can use 'C<+>' to disable any chomping options (i.e. leave the
-whitespace intact) on a per-directive basis.
-
- [% FOREACH user IN userlist %]
- User: [% user +%]
- [% END %]
-
-With C<POST_CHOMP> set to C<CHOMP_ONE>, the above example would be parsed as
-if written:
-
- [% FOREACH user IN userlist %]User: [% user %]
- [% END %]
-
-For reference, the C<PRE_CHOMP> and C<POST_CHOMP> configuration options may be
-set to any of the following:
-
- Constant Value Tag Modifier
- ----------------------------------
- CHOMP_NONE 0 +
- CHOMP_ONE 1 -
- CHOMP_COLLAPSE 2 =
- CHOMP_GREEDY 3 ~
-
-=head2 TRIM
-
-The C<TRIM> option can be set to have any leading and trailing whitespace
-automatically removed from the output of all template files and C<BLOCK>s.
-
-By example, the following C<BLOCK> definition
-
- [% BLOCK foo %]
- Line 1 of foo
- [% END %]
-
-will be processed is as "C<\nLine 1 of foo\n>". When C<INCLUDE>d, the surrounding
-newlines will also be introduced.
-
- before
- [% INCLUDE foo %]
- after
-
-Generated output:
-
- before
-
- Line 1 of foo
-
- after
-
-With the C<TRIM> option set to any true value, the leading and trailing
-newlines (which count as whitespace) will be removed from the output
-of the C<BLOCK>.
-
- before
- Line 1 of foo
- after
-
-The C<TRIM> option is disabled (C<0>) by default.
-
-=head2 INTERPOLATE
-
-The C<INTERPOLATE> flag, when set to any true value will cause variable
-references in plain text (i.e. not surrounded by C<START_TAG> and C<END_TAG>)
-to be recognised and interpolated accordingly.
-
- my $template = Template->new({
- INTERPOLATE => 1,
- });
-
-Variables should be prefixed by a 'C<$>' to identify them. Curly braces
-can be used in the familiar Perl/shell style to explicitly scope the
-variable name where required.
-
- # INTERPOLATE => 0
- <a href="http://[% server %]/[% help %]">
- <img src="[% images %]/help.gif"></a>
- [% myorg.name %]
-
- # INTERPOLATE => 1
- <a href="http://$server/$help">
- <img src="$images/help.gif"></a>
- $myorg.name
-
- # explicit scoping with { }
- <img src="$images/${icon.next}.gif">
-
-Note that a limitation in Perl's regex engine restricts the maximum length
-of an interpolated template to around 32 kilobytes or possibly less. Files
-that exceed this limit in size will typically cause Perl to dump core with
-a segmentation fault. If you routinely process templates of this size
-then you should disable C<INTERPOLATE> or split the templates in several
-smaller files or blocks which can then be joined backed together via
-C<PROCESS> or C<INCLUDE>.
-
-=head2 ANYCASE
-
-By default, directive keywords should be expressed in UPPER CASE. The
-C<ANYCASE> option can be set to allow directive keywords to be specified
-in any case.
-
- # ANYCASE => 0 (default)
- [% INCLUDE foobar %] # OK
- [% include foobar %] # ERROR
- [% include = 10 %] # OK, 'include' is a variable
-
- # ANYCASE => 1
- [% INCLUDE foobar %] # OK
- [% include foobar %] # OK
- [% include = 10 %] # ERROR, 'include' is reserved word
-
-One side-effect of enabling C<ANYCASE> is that you cannot use a variable
-of the same name as a reserved word, regardless of case. The reserved
-words are currently:
-
- GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
- IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
- USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
- TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
- CLEAR TO STEP AND OR NOT MOD DIV END
-
-The only lower case reserved words that cannot be used for variables,
-regardless of the C<ANYCASE> option, are the operators:
-
- and or not mod div
-
-=head1 Template Files and Blocks
-
-=head2 INCLUDE_PATH
-
-The C<INCLUDE_PATH> is used to specify one or more directories in which
-template files are located. When a template is requested that isn't
-defined locally as a C<BLOCK>, each of the C<INCLUDE_PATH> directories is
-searched in turn to locate the template file. Multiple directories
-can be specified as a reference to a list or as a single string where
-each directory is delimited by 'C<:>'.
-
- my $template = Template->new({
- INCLUDE_PATH => '/usr/local/templates',
- });
-
- my $template = Template->new({
- INCLUDE_PATH => '/usr/local/templates:/tmp/my/templates',
- });
-
- my $template = Template->new({
- INCLUDE_PATH => [ '/usr/local/templates',
- '/tmp/my/templates' ],
- });
-
-On Win32 systems, a little extra magic is invoked, ignoring delimiters
-that have 'C<:>' followed by a 'C</>' or 'C<\>'. This avoids confusion when using
-directory names like 'C<C:\Blah Blah>'.
-
-When specified as a list, the C<INCLUDE_PATH> path can contain elements
-which dynamically generate a list of C<INCLUDE_PATH> directories. These
-generator elements can be specified as a reference to a subroutine or
-an object which implements a C<paths()> method.
-
- my $template = Template->new({
- INCLUDE_PATH => [ '/usr/local/templates',
- \&incpath_generator,
- My::IncPath::Generator->new( ... ) ],
- });
-
-Each time a template is requested and the C<INCLUDE_PATH> examined, the
-subroutine or object method will be called. A reference to a list of
-directories should be returned. Generator subroutines should report
-errors using C<die()>. Generator objects should return undef and make an
-error available via its C<error()> method.
-
-For example:
-
- sub incpath_generator {
- # ...some code...
-
- if ($all_is_well) {
- return \@list_of_directories;
- }
- else {
- die "cannot generate INCLUDE_PATH...\n";
- }
- }
-
-or:
-
- package My::IncPath::Generator;
-
- # Template::Base (or Class::Base) provides error() method
- use Template::Base;
- use base qw( Template::Base );
-
- sub paths {
- my $self = shift;
-
- # ...some code...
-
- if ($all_is_well) {
- return \@list_of_directories;
- }
- else {
- return $self->error("cannot generate INCLUDE_PATH...\n");
- }
- }
-
- 1;
-
-=head2 DELIMITER
-
-Used to provide an alternative delimiter character sequence for
-separating paths specified in the C<INCLUDE_PATH>. The default
-value for C<DELIMITER> is 'C<:>'.
-
- my $template = Template->new({
- DELIMITER => '; ',
- INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN',
- });
-
-On Win32 systems, the default delimiter is a little more intelligent,
-splitting paths only on 'C<:>' characters that aren't followed by a 'C</>'.
-This means that the following should work as planned, splitting the
-C<INCLUDE_PATH> into 2 separate directories, C<C:/foo> and C<C:/bar>.
-
- # on Win32 only
- my $template = Template->new({
- INCLUDE_PATH => 'C:/Foo:C:/Bar'
- });
-
-However, if you're using Win32 then it's recommended that you
-explicitly set the C<DELIMITER> character to something else (e.g. 'C<;>')
-rather than rely on this subtle magic.
-
-=head2 ABSOLUTE
-
-The C<ABSOLUTE> flag is used to indicate if templates specified with
-absolute filenames (e.g. 'C</foo/bar>') should be processed. It is
-disabled by default and any attempt to load a template by such a
-name will cause a 'C<file>' exception to be raised.
-
- my $template = Template->new({
- ABSOLUTE => 1,
- });
-
- # this is why it's disabled by default
- [% INSERT /etc/passwd %]
-
-On Win32 systems, the regular expression for matching absolute
-pathnames is tweaked slightly to also detect filenames that start
-with a driver letter and colon, such as:
-
- C:/Foo/Bar
-
-=head2 RELATIVE
-
-The C<RELATIVE> flag is used to indicate if templates specified with
-filenames relative to the current directory (e.g. 'C<./foo/bar>' or
-'C<../../some/where/else>') should be loaded. It is also disabled by
-default, and will raise a 'C<file>' error if such template names are
-encountered.
-
- my $template = Template->new({
- RELATIVE => 1,
- });
-
- [% INCLUDE ../logs/error.log %]
-
-=head2 DEFAULT
-
-The C<DEFAULT> option can be used to specify a default template which should
-be used whenever a specified template can't be found in the C<INCLUDE_PATH>.
-
- my $template = Template->new({
- DEFAULT => 'notfound.html',
- });
-
-If a non-existent template is requested through the Template
-L<process()|Template#process()> method, or by an C<INCLUDE>, C<PROCESS> or
-C<WRAPPER> directive, then the C<DEFAULT> template will instead be processed, if
-defined. Note that the C<DEFAULT> template is not used when templates are
-specified with absolute or relative filenames, or as a reference to a input
-file handle or text string.
-
-=head2 BLOCKS
-
-The C<BLOCKS> option can be used to pre-define a default set of template
-blocks. These should be specified as a reference to a hash array
-mapping template names to template text, subroutines or L<Template::Document>
-objects.
-
- my $template = Template->new({
- BLOCKS => {
- header => 'The Header. [% title %]',
- footer => sub { return $some_output_text },
- another => Template::Document->new({ ... }),
- },
- });
-
-=head2 VIEWS
-
-The VIEWS option can be used to define one or more L<Template::View>
-objects. They can be specified as a reference to a hash array or list
-reference.
-
- my $template = Template->new({
- VIEWS => {
- my_view => { prefix => 'my_templates/' },
- },
- });
-
-Be aware of the fact that Perl's hash array are unordered, so if you want to
-specify multiple views of which one or more are based on other views, then
-you should use a list reference to preserve the order of definition.
-
- my $template = Template->new({
- VIEWS => [
- bottom => { prefix => 'bottom/' },
- middle => { prefix => 'middle/', base => 'bottom' },
- top => { prefix => 'top/', base => 'middle' },
- ],
- });
-
-=head2 AUTO_RESET
-
-The C<AUTO_RESET> option is set by default and causes the local C<BLOCKS>
-cache for the L<Template::Context> object to be reset on each call to the
-Template L<process()|Template#process()> method. This ensures that any C<BLOCK>s
-defined within a template will only persist until that template is finished
-processing. This prevents C<BLOCK>s defined in one processing request from
-interfering with other independent requests subsequently processed by the same
-context object.
-
-The C<BLOCKS> item may be used to specify a default set of block definitions
-for the L<Template::Context> object. Subsequent C<BLOCK> definitions in
-templates will over-ride these but they will be reinstated on each reset if
-C<AUTO_RESET> is enabled (default), or if the L<Template::Context>
-L<reset()|Template::Context#reset()> method is called.
-
-=head2 RECURSION
-
-The template processor will raise a file exception if it detects
-direct or indirect recursion into a template. Setting this option to
-any true value will allow templates to include each other recursively.
-
-=head1 Template Variables
-
-=head2 VARIABLES
-
-The C<VARIABLES> option (or C<PRE_DEFINE> - they're equivalent) can be used
-to specify a hash array of template variables that should be used to
-pre-initialise the stash when it is created. These items are ignored
-if the C<STASH> item is defined.
-
- my $template = Template->new({
- VARIABLES => {
- title => 'A Demo Page',
- author => 'Joe Random Hacker',
- version => 3.14,
- },
- };
-
-or
-
- my $template = Template->new({
- PRE_DEFINE => {
- title => 'A Demo Page',
- author => 'Joe Random Hacker',
- version => 3.14,
- },
- };
-
-=head2 CONSTANTS
-
-The C<CONSTANTS> option can be used to specify a hash array of template
-variables that are compile-time constants. These variables are
-resolved once when the template is compiled, and thus don't require
-further resolution at runtime. This results in significantly faster
-processing of the compiled templates and can be used for variables that
-don't change from one request to the next.
-
- my $template = Template->new({
- CONSTANTS => {
- title => 'A Demo Page',
- author => 'Joe Random Hacker',
- version => 3.14,
- },
- };
-
-=head2 CONSTANT_NAMESPACE
-
-Constant variables are accessed via the C<constants> namespace by
-default.
-
- [% constants.title %]
-
-The C<CONSTANTS_NAMESPACE> option can be set to specify an alternate
-namespace.
-
- my $template = Template->new({
- CONSTANTS => {
- title => 'A Demo Page',
- # ...etc...
- },
- CONSTANTS_NAMESPACE => 'const',
- };
-
-In this case the constants would then be accessed as:
-
- [% const.title %]
-
-=head2 NAMESPACE
-
-The constant folding mechanism described above is an example of a
-namespace handler. Namespace handlers can be defined to provide
-alternate parsing mechanisms for variables in different namespaces.
-
-Under the hood, the L<Template> module converts a constructor configuration
-such as:
-
- my $template = Template->new({
- CONSTANTS => {
- title => 'A Demo Page',
- # ...etc...
- },
- CONSTANTS_NAMESPACE => 'const',
- };
-
-into one like:
-
- my $template = Template->new({
- NAMESPACE => {
- const => Template:::Namespace::Constants->new({
- title => 'A Demo Page',
- # ...etc...
- }),
- },
- };
-
-You can use this mechanism to define multiple constant namespaces, or
-to install custom handlers of your own.
-
- my $template = Template->new({
- NAMESPACE => {
- site => Template:::Namespace::Constants->new({
- title => "Wardley's Widgets",
- version => 2.718,
- }),
- author => Template:::Namespace::Constants->new({
- name => 'Andy Wardley',
- email => 'abw@andywardley.com',
- }),
- voodoo => My::Namespace::Handler->new( ... ),
- },
- };
-
-Now you have two constant namespaces, for example:
-
- [% site.title %]
- [% author.name %]
-
-as well as your own custom namespace handler installed for the 'voodoo'
-namespace.
-
- [% voodoo.magic %]
-
-See L<Template::Namespace::Constants>
-for an example of what a namespace handler looks like on the inside.
-
-=head1 Template Processing Options
-
-The following options are used to specify any additional templates that should
-be processed before, after, around or instead of the template passed as the
-first argument to the L<Template> L<process()|Template#process()> method.
-These options can be perform various useful tasks such as adding standard
-headers or footers to all pages, wrapping page output in other templates,
-pre-defining variables or performing initialisation or cleanup tasks,
-automatically generating page summary information, navigation elements, and so
-on.
-
-The task of processing the template is delegated internally to the
-L<Template::Service> module which, unsurprisingly, also has a
-L<process()|Template::Service#process()> method. Any templates defined by the
-C<PRE_PROCESS> option are processed first and any output generated is added to
-the output buffer. Then the main template is processed, or if one or more
-C<PROCESS> templates are defined then they are instead processed in turn. In this
-case, one of the C<PROCESS> templates is responsible for processing the main
-template, by a directive such as:
-
- [% PROCESS $template %]
-
-The output of processing the main template or the C<PROCESS> template(s)
-is then wrapped in any C<WRAPPER> templates, if defined. C<WRAPPER>
-templates don't need to worry about explicitly processing the template
-because it will have been done for them already. Instead C<WRAPPER>
-templates access the content they are wrapping via the C<content>
-variable.
-
- wrapper before
- [% content %]
- wrapper after
-
-This output generated from processing the main template, and/or any
-C<PROCESS> or C<WRAPPER> templates is added to the output buffer. Finally,
-any C<POST_PROCESS> templates are processed and their output is also
-added to the output buffer which is then returned.
-
-If the main template throws an exception during processing then any relevant
-template(s) defined via the C<ERROR> option will be processed instead. If
-defined and successfully processed, the output from the error template will be
-added to the output buffer in place of the template that generated the error
-and processing will continue, applying any C<WRAPPER> and C<POST_PROCESS>
-templates. If no relevant C<ERROR> option is defined, or if the error occurs
-in one of the C<PRE_PROCESS>, C<WRAPPER> or C<POST_PROCESS> templates, then
-the process will terminate immediately and the error will be returned.
-
-=head2 PRE_PROCESS, POST_PROCESS
-
-These values may be set to contain the name(s) of template files
-(relative to C<INCLUDE_PATH>) which should be processed immediately
-before and/or after each template. These do not get added to
-templates processed into a document via directives such as C<INCLUDE>,
-C<PROCESS>, C<WRAPPER> etc.
-
- my $template = Template->new({
- PRE_PROCESS => 'header',
- POST_PROCESS => 'footer',
- };
-
-Multiple templates may be specified as a reference to a list. Each is
-processed in the order defined.
-
- my $template = Template->new({
- PRE_PROCESS => [ 'config', 'header' ],
- POST_PROCESS => 'footer',
- };
-
-Alternately, multiple template may be specified as a single string,
-delimited by 'C<:>'. This delimiter string can be changed via the
-C<DELIMITER> option.
-
- my $template = Template->new({
- PRE_PROCESS => 'config:header',
- POST_PROCESS => 'footer',
- };
-
-The C<PRE_PROCESS> and C<POST_PROCESS> templates are evaluated in the same
-variable context as the main document and may define or update
-variables for subsequent use.
-
-config:
-
- [% # set some site-wide variables
- bgcolor = '#ffffff'
- version = 2.718
- %]
-
-header:
-
- [% DEFAULT title = 'My Funky Web Site' %]
- <html>
- <head>
- <title>[% title %]</title>
- </head>
- <body bgcolor="[% bgcolor %]">
-
-footer:
-
- <hr>
- Version [% version %]
- </body>
- </html>
-
-The L<Template::Document> object representing the main template being processed
-is available within C<PRE_PROCESS> and C<POST_PROCESS> templates as the C<template>
-variable. Metadata items defined via the C<META> directive may be accessed
-accordingly.
-
- $template->process('mydoc.html', $vars);
-
-mydoc.html:
-
- [% META title = 'My Document Title' %]
- blah blah blah
- ...
-
-header:
-
- <html>
- <head>
- <title>[% template.title %]</title>
- </head>
- <body bgcolor="[% bgcolor %]">
-
-=head2 PROCESS
-
-The C<PROCESS> option may be set to contain the name(s) of template files
-(relative to C<INCLUDE_PATH>) which should be processed instead of the main
-template passed to the L<Template> L<process()|Template#process()> method.
-This can be used to apply consistent wrappers around all templates, similar to
-the use of C<PRE_PROCESS> and C<POST_PROCESS> templates.
-
- my $template = Template->new({
- PROCESS => 'content',
- };
-
- # processes 'content' instead of 'foo.html'
- $template->process('foo.html');
-
-A reference to the original template is available in the C<template>
-variable. Metadata items can be inspected and the template can be
-processed by specifying it as a variable reference (i.e. prefixed by
-C<$>) to an C<INCLUDE>, C<PROCESS> or C<WRAPPER> directive.
-
-content:
-
- <html>
- <head>
- <title>[% template.title %]</title>
- </head>
- <body>
- <!-- begin content -->
- [% PROCESS $template %]
- <!-- end content -->
- <hr>
- © Copyright [% template.copyright %]
- </body>
- </html>
-
-foo.html:
-
- [% META
- title = 'The Foo Page'
- author = 'Fred Foo'
- copyright = '2000 Fred Foo'
- %]
- <h1>[% template.title %]</h1>
- Welcome to the Foo Page, blah blah blah
-
-output:
-
- <html>
- <head>
- <title>The Foo Page</title>
- </head>
- <body>
- <!-- begin content -->
- <h1>The Foo Page</h1>
- Welcome to the Foo Page, blah blah blah
- <!-- end content -->
- <hr>
- © Copyright 2000 Fred Foo
- </body>
- </html>
-
-=head2 WRAPPER
-
-The C<WRAPPER> option can be used to specify one or more templates which
-should be used to wrap around the output of the main page template.
-The main template is processed first (or any C<PROCESS> template(s)) and
-the output generated is then passed as the C<content> variable to the
-C<WRAPPER> template(s) as they are processed.
-
- my $template = Template->new({
- WRAPPER => 'wrapper',
- };
-
- # process 'foo' then wrap in 'wrapper'
- $template->process('foo', { message => 'Hello World!' });
-
-wrapper:
-
- <wrapper>
- [% content %]
- </wrapper>
-
-foo:
-
- This is the foo file!
- Message: [% message %]
-
-The output generated from this example is:
-
- <wrapper>
- This is the foo file!
- Message: Hello World!
- </wrapper>
-
-You can specify more than one C<WRAPPER> template by setting the value to
-be a reference to a list of templates. The C<WRAPPER> templates will be
-processed in reverse order with the output of each being passed to the
-next (or previous, depending on how you look at it) as the 'content'
-variable. It sounds complicated, but the end result is that it just
-"Does The Right Thing" to make wrapper templates nest in the order you
-specify.
-
- my $template = Template->new({
- WRAPPER => [ 'outer', 'inner' ],
- };
-
- # process 'foo' then wrap in 'inner', then in 'outer'
- $template->process('foo', { message => 'Hello World!' });
-
-outer:
-
- <outer>
- [% content %]
- </outer>
-
-inner:
-
- <inner>
- [% content %]
- </inner>
-
-The output generated is then:
-
- <outer>
- <inner>
- This is the foo file!
- Message: Hello World!
- </inner>
- </outer>
-
-One side-effect of the "inside-out" processing of the C<WRAPPER>
-configuration item (and also the C<WRAPPER> directive) is that any
-variables set in the template being wrapped will be visible to the
-template doing the wrapping, but not the other way around.
-
-You can use this to good effect in allowing page templates to set
-pre-defined values which are then used in the wrapper templates. For
-example, our main page template 'foo' might look like this:
-
-foo:
-
- [% page = {
- title = 'Foo Page'
- subtitle = 'Everything There is to Know About Foo'
- author = 'Frank Oliver Octagon'
- }
- %]
-
- <p>
- Welcome to the page that tells you everything about foo
- blah blah blah...
- </p>
-
-The C<foo> template is processed before the wrapper template meaning
-that the C<page> data structure will be defined for use in the wrapper
-template.
-
-wrapper:
-
- <html>
- <head>
- <title>[% page.title %]</title>
- </head>
- <body>
- <h1>[% page.title %]</h1>
- <h2>[% page.subtitle %]</h1>
- <h3>by [% page.author %]</h3>
- [% content %]
- </body>
- </html>
-
-It achieves the same effect as defining C<META> items which are then
-accessed via the C<template> variable (which you are still free to
-use within C<WRAPPER> templates), but gives you more flexibility in
-the type and complexity of data that you can define.
-
-=head2 ERROR
-
-The C<ERROR> (or C<ERRORS> if you prefer) configuration item can be used to
-name a single template or specify a hash array mapping exception types
-to templates which should be used for error handling. If an uncaught
-exception is raised from within a template then the appropriate error
-template will instead be processed.
-
-If specified as a single value then that template will be processed
-for all uncaught exceptions.
-
- my $template = Template->new({
- ERROR => 'error.html'
- });
-
-If the C<ERROR> item is a hash reference the keys are assumed to be
-exception types and the relevant template for a given exception will
-be selected. A C<default> template may be provided for the general
-case. Note that C<ERROR> can be pluralised to C<ERRORS> if you find
-it more appropriate in this case.
-
- my $template = Template->new({
- ERRORS => {
- user => 'user/index.html',
- dbi => 'error/database',
- default => 'error/default',
- },
- });
-
-In this example, any C<user> exceptions thrown will cause the
-F<user/index.html> template to be processed, C<dbi> errors are handled
-by F<error/database> and all others by the F<error/default> template.
-Any C<PRE_PROCESS> and/or C<POST_PROCESS> templates will also be applied
-to these error templates.
-
-Note that exception types are hierarchical and a C<foo> handler will
-catch all C<foo.*> errors (e.g. C<foo.bar>, C<foo.bar.baz>) if a more
-specific handler isn't defined. Be sure to quote any exception types
-that contain periods to prevent Perl concatenating them into a single
-string (i.e. C<user.passwd> is parsed as C<'user'.'passwd'>).
-
- my $template = Template->new({
- ERROR => {
- 'user.login' => 'user/login.html',
- 'user.passwd' => 'user/badpasswd.html',
- 'user' => 'user/index.html',
- 'default' => 'error/default',
- },
- });
-
-In this example, any template processed by the C<$template> object, or
-other templates or code called from within, can raise a C<user.login>
-exception and have the service redirect to the F<user/login.html>
-template. Similarly, a C<user.passwd> exception has a specific
-handling template, F<user/badpasswd.html>, while all other C<user> or
-C<user.*> exceptions cause a redirection to the F<user/index.html> page.
-All other exception types are handled by F<error/default>.
-
-Exceptions can be raised in a template using the C<THROW> directive,
-
- [% THROW user.login 'no user id: please login' %]
-
-or by calling the L<throw()|Template::Context#throw()> method on the
-current L<Template::Context> object,
-
- $context->throw('user.passwd', 'Incorrect Password');
- $context->throw('Incorrect Password'); # type 'undef'
-
-or from Perl code by calling C<die()> with a L<Template::Exception> object,
-
- die (Template::Exception->new('user.denied', 'Invalid User ID'));
-
-or by simply calling L<die()> with an error string. This is
-automagically caught and converted to an exception of 'C<undef>'
-type which can then be handled in the usual way.
-
- die "I'm sorry Dave, I can't do that";
-
-Note that the 'C<undef>' we're talking about here is a literal string
-rather than Perl's C<undef> used to represent undefined values.
-
-=head1 Template Runtime Options
-
-=head2 EVAL_PERL
-
-This flag is used to indicate if C<PERL> and/or C<RAWPERL> blocks should be
-evaluated. It is disabled by default and any C<PERL> or C<RAWPERL> blocks
-encountered will raise exceptions of type 'C<perl>' with the message
-'C<EVAL_PERL not set>'. Note however that any C<RAWPERL> blocks should
-always contain valid Perl code, regardless of the C<EVAL_PERL> flag. The
-parser will fail to compile templates that contain invalid Perl code
-in C<RAWPERL> blocks and will throw a 'C<file>' exception.
-
-When using compiled templates (see
-L<Caching and Compiling Options>),
-the C<EVAL_PERL> has an affect when the template is compiled, and again
-when the templates is subsequently processed, possibly in a different
-context to the one that compiled it.
-
-If the C<EVAL_PERL> is set when a template is compiled, then all C<PERL> and
-C<RAWPERL> blocks will be included in the compiled template. If the
-C<EVAL_PERL> option isn't set, then Perl code will be generated which
-B<always> throws a 'C<perl>' exception with the message 'C<EVAL_PERL not
-set>' B<whenever> the compiled template code is run.
-
-Thus, you must have C<EVAL_PERL> set if you want your compiled templates
-to include C<PERL> and C<RAWPERL> blocks.
-
-At some point in the future, using a different invocation of the
-Template Toolkit, you may come to process such a pre-compiled
-template. Assuming the C<EVAL_PERL> option was set at the time the
-template was compiled, then the output of any C<RAWPERL> blocks will be
-included in the compiled template and will get executed when the
-template is processed. This will happen regardless of the runtime
-C<EVAL_PERL> status.
-
-Regular C<PERL> blocks are a little more cautious, however. If the
-C<EVAL_PERL> flag isn't set for the I<current> context, that is, the
-one which is trying to process it, then it will throw the familiar 'C<perl>'
-exception with the message, 'C<EVAL_PERL not set>'.
-
-Thus you can compile templates to include C<PERL> blocks, but optionally
-disable them when you process them later. Note however that it is
-possible for a C<PERL> block to contain a Perl "C<BEGIN { # some code }>"
-block which will always get run regardless of the runtime C<EVAL_PERL>
-status. Thus, if you set C<EVAL_PERL> when compiling templates, it is
-assumed that you trust the templates to Do The Right Thing. Otherwise
-you must accept the fact that there's no bulletproof way to prevent
-any included code from trampling around in the living room of the
-runtime environment, making a real nuisance of itself if it really
-wants to. If you don't like the idea of such uninvited guests causing
-a bother, then you can accept the default and keep C<EVAL_PERL> disabled.
-
-=head2 OUTPUT
-
-Default output location or handler. This may be specified as one of:
-a file name (relative to C<OUTPUT_PATH>, if defined, or the current
-working directory if not specified absolutely); a file handle
-(e.g. C<GLOB> or L<IO::Handle>) opened for writing; a reference to a text
-string to which the output is appended (the string isn't cleared); a
-reference to a subroutine which is called, passing the output text as
-an argument; as a reference to an array, onto which the content will be
-C<push()>ed; or as a reference to any object that supports the C<print()>
-method. This latter option includes the C<Apache::Request> object which
-is passed as the argument to Apache/mod_perl handlers.
-
-example 1 (file name):
-
- my $template = Template->new({
- OUTPUT => "/tmp/foo",
- });
-
-example 2 (text string):
-
- my $output = '';
- my $template = Template->new({
- OUTPUT => \$output,
- });
-
-example 3 (file handle):
-
- open (TOUT, "> $file") || die "$file: $!\n";
- my $template = Template->new({
- OUTPUT => \*TOUT,
- });
-
-example 4 (subroutine):
-
- sub output { my $out = shift; print "OUTPUT: $out" }
- my $template = Template->new({
- OUTPUT => \&output,
- });
-
-example 5 (array reference):
-
- my $template = Template->new({
- OUTPUT => \@output,
- })
-
-example 6 (Apache/mod_perl handler):
-
- sub handler {
- my $r = shift;
- my $t = Template->new({
- OUTPUT => $r,
- });
- ...
- }
-
-The default C<OUTPUT> location be overridden by passing a third parameter to
-the L<Template> L<process()|Template#process()> method. This can be specified
-as any of the above argument types.
-
- $t->process($file, $vars, "/tmp/foo");
- $t->process($file, $vars, \$output);
- $t->process($file, $vars, \*MYGLOB);
- $t->process($file, $vars, \@output);
- $t->process($file, $vars, $r); # Apache::Request
- ...
-
-=head2 OUTPUT_PATH
-
-The C<OUTPUT_PATH> allows a directory to be specified into which output
-files should be written. An output file can be specified by the
-C<OUTPUT> option, or passed by name as the third parameter to the
-L<Template> L<process()|Template#process()> method.
-
- my $template = Template->new({
- INCLUDE_PATH => "/tmp/src",
- OUTPUT_PATH => "/tmp/dest",
- });
-
- my $vars = {
- ...
- };
-
- foreach my $file ('foo.html', 'bar.html') {
- $template->process($file, $vars, $file)
- || die $template->error();
- }
-
-This example will read the input files F</tmp/src/foo.html> and
-F</tmp/src/bar.html> and write the processed output to F</tmp/dest/foo.html>
-and F</tmp/dest/bar.html>, respectively.
-
-=head2 STRICT
-
-By default the Template Toolkit will silently ignore the use of undefined
-variables (a bad design decision that I regret).
-
-When the C<STRICT> option is set, the use of any undefined variables or
-values will cause an exception to be throw. The exception will have a
-C<type> of C<var.undefined> and a message of the form
-"undefined variable: xxx".
-
- my $template = Template->new(
- STRICT => 1
- );
-
-=head2 DEBUG
-
-The C<DEBUG> option can be used to enable debugging within the various
-different modules that comprise the Template Toolkit. The
-L<Template::Constants> module defines a set of
-C<DEBUG_XXXX> constants which can be combined using the logical OR
-operator, 'C<|>'.
-
- use Template::Constants qw( :debug );
-
- my $template = Template->new({
- DEBUG => DEBUG_PARSER | DEBUG_PROVIDER,
- });
-
-For convenience, you can also provide a string containing a list
-of lower case debug options, separated by any non-word characters.
-
- my $template = Template->new({
- DEBUG => 'parser, provider',
- });
-
-The following C<DEBUG_XXXX> flags can be used:
-
-=over 4
-
-=item DEBUG_SERVICE
-
-Enables general debugging messages for the
-L<Template::Service> module.
-
-=item DEBUG_CONTEXT
-
-Enables general debugging messages for the
-L<Template::Context> module.
-
-=item DEBUG_PROVIDER
-
-Enables general debugging messages for the
-L<Template::Provider> module.
-
-=item DEBUG_PLUGINS
-
-Enables general debugging messages for the
-L<Template::Plugins> module.
-
-=item DEBUG_FILTERS
-
-Enables general debugging messages for the
-L<Template::Filters> module.
-
-=item DEBUG_PARSER
-
-This flag causes the L<Template::Parser> to generate
-debugging messages that show the Perl code generated by parsing and
-compiling each template.
-
-=item DEBUG_UNDEF
-
-This option causes the Template Toolkit to throw an 'C<undef>' error
-whenever it encounters an undefined variable value.
-
-=item DEBUG_DIRS
-
-This option causes the Template Toolkit to generate comments
-indicating the source file, line and original text of each directive
-in the template. These comments are embedded in the template output
-using the format defined in the C<DEBUG_FORMAT> configuration item, or a
-simple default format if unspecified.
-
-For example, the following template fragment:
-
- Hello World
-
-would generate this output:
-
- ## input text line 1 : ##
- Hello
- ## input text line 2 : World ##
- World
-
-=item DEBUG_ALL
-
-Enables all debugging messages.
-
-=item DEBUG_CALLER
-
-This option causes all debug messages that aren't newline terminated
-to have the file name and line number of the caller appended to them.
-
-=back
-
-=head2 DEBUG_FORMAT
-
-The C<DEBUG_FORMAT> option can be used to specify a format string for the
-debugging messages generated via the C<DEBUG_DIRS> option described
-above. Any occurrences of C<$file>, C<$line> or C<$text> will be
-replaced with the current file name, line or directive text,
-respectively. Notice how the format is single quoted to prevent Perl
-from interpolating those tokens as variables.
-
- my $template = Template->new({
- DEBUG => 'dirs',
- DEBUG_FORMAT => '<!-- $file line $line : [% $text %] -->',
- });
-
-The following template fragment:
-
- [% foo = 'World' %]
- Hello [% foo %]
-
-would then generate this output:
-
- <!-- input text line 2 : [% foo = 'World' %] -->
- Hello <!-- input text line 3 : [% foo %] -->World
-
-The DEBUG directive can also be used to set a debug format within
-a template.
-
- [% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
-
-=head1 Caching and Compiling Options
-
-=head2 CACHE_SIZE
-
-The L<Template::Provider> module caches compiled templates to avoid the need
-to re-parse template files or blocks each time they are used. The C<CACHE_SIZE>
-option is used to limit the number of compiled templates that the module
-should cache.
-
-By default, the C<CACHE_SIZE> is undefined and all compiled templates are
-cached. When set to any positive value, the cache will be limited to
-storing no more than that number of compiled templates. When a new
-template is loaded and compiled and the cache is full (i.e. the number
-of entries == C<CACHE_SIZE>), the least recently used compiled template
-is discarded to make room for the new one.
-
-The C<CACHE_SIZE> can be set to C<0> to disable caching altogether.
-
- my $template = Template->new({
- CACHE_SIZE => 64, # only cache 64 compiled templates
- });
-
- my $template = Template->new({
- CACHE_SIZE => 0, # don't cache any compiled templates
- });
-
-As well as caching templates as they are found, the L<Template::Provider>
-also implements negative caching to keep track of templates that are
-I<not> found. This allows the provider to quickly decline a request
-for a template that it has previously failed to locate, saving the effort
-of going to look for it again. This is useful when an C<INCLUDE_PATH> includes
-multiple providers, ensuring that the request is passed down through the
-providers as quickly as possible.
-
-=head2 STAT_TTL
-
-This value can be set to control how long the L<Template::Provider> will keep a
-template cached in memory before checking to see if the source template has
-changed.
-
- my $provider = Template::Provider->new({
- STAT_TTL => 60, # one minute
- });
-
-The default value is 1 (second). You'll probably want to set this to a higher
-value if you're running the Template Toolkit inside a persistent web server
-application (e.g. mod_perl). For example, set it to 60 and the provider will
-only look for changes to templates once a minute at most. However, during
-development (or any time you're making frequent changes to templates) you'll
-probably want to keep it set to a low value so that you don't have to wait
-for the provider to notice that your templates have changed.
-
-=head2 COMPILE_EXT
-
-From version 2 onwards, the Template Toolkit has the ability to
-compile templates to Perl code and save them to disk for subsequent
-use (i.e. cache persistence). The C<COMPILE_EXT> option may be
-provided to specify a filename extension for compiled template files.
-It is undefined by default and no attempt will be made to read or write
-any compiled template files.
-
- my $template = Template->new({
- COMPILE_EXT => '.ttc',
- });
-
-If C<COMPILE_EXT> is defined (and C<COMPILE_DIR> isn't, see below) then compiled
-template files with the C<COMPILE_EXT> extension will be written to the same
-directory from which the source template files were loaded.
-
-Compiling and subsequent reuse of templates happens automatically
-whenever the C<COMPILE_EXT> or C<COMPILE_DIR> options are set. The Template
-Toolkit will automatically reload and reuse compiled files when it
-finds them on disk. If the corresponding source file has been modified
-since the compiled version as written, then it will load and re-compile
-the source and write a new compiled version to disk.
-
-This form of cache persistence offers significant benefits in terms of
-time and resources required to reload templates. Compiled templates can
-be reloaded by a simple call to Perl's C<require()>, leaving Perl to handle
-all the parsing and compilation. This is a Good Thing.
-
-=head2 COMPILE_DIR
-
-The C<COMPILE_DIR> option is used to specify an alternate directory root
-under which compiled template files should be saved.
-
- my $template = Template->new({
- COMPILE_DIR => '/tmp/ttc',
- });
-
-The C<COMPILE_EXT> option may also be specified to have a consistent file
-extension added to these files.
-
- my $template1 = Template->new({
- COMPILE_DIR => '/tmp/ttc',
- COMPILE_EXT => '.ttc1',
- });
-
- my $template2 = Template->new({
- COMPILE_DIR => '/tmp/ttc',
- COMPILE_EXT => '.ttc2',
- });
-
-When C<COMPILE_EXT> is undefined, the compiled template files have the
-same name as the original template files, but reside in a different
-directory tree.
-
-Each directory in the C<INCLUDE_PATH> is replicated in full beneath the
-C<COMPILE_DIR> directory. This example:
-
- my $template = Template->new({
- COMPILE_DIR => '/tmp/ttc',
- INCLUDE_PATH => '/home/abw/templates:/usr/share/templates',
- });
-
-would create the following directory structure:
-
- /tmp/ttc/home/abw/templates/
- /tmp/ttc/usr/share/templates/
-
-Files loaded from different C<INCLUDE_PATH> directories will have their
-compiled forms save in the relevant C<COMPILE_DIR> directory.
-
-On Win32 platforms a filename may by prefixed by a drive letter and
-colon. e.g.
-
- C:/My Templates/header
-
-The colon will be silently stripped from the filename when it is added
-to the C<COMPILE_DIR> value(s) to prevent illegal filename being generated.
-Any colon in C<COMPILE_DIR> elements will be left intact. For example:
-
- # Win32 only
- my $template = Template->new({
- DELIMITER => ';',
- COMPILE_DIR => 'C:/TT2/Cache',
- INCLUDE_PATH => 'C:/TT2/Templates;D:/My Templates',
- });
-
-This would create the following cache directories:
-
- C:/TT2/Cache/C/TT2/Templates
- C:/TT2/Cache/D/My Templates
-
-=head1 Plugins and Filters
-
-=head2 PLUGINS
-
-The C<PLUGINS> options can be used to provide a reference to a hash array
-that maps plugin names to Perl module names. A number of standard
-plugins are defined (e.g. C<table>, C<format>, C<cgi>, etc.) which map to
-their corresponding C<Template::Plugin::*> counterparts. These can be
-redefined by values in the C<PLUGINS> hash.
-
- my $template = Template->new({
- PLUGINS => {
- cgi => 'MyOrg::Template::Plugin::CGI',
- foo => 'MyOrg::Template::Plugin::Foo',
- bar => 'MyOrg::Template::Plugin::Bar',
- },
- });
-
-The recommended convention is to specify these plugin names in lower
-case. The Template Toolkit first looks for an exact case-sensitive
-match and then tries the lower case conversion of the name specified.
-
- [% USE Foo %] # look for 'Foo' then 'foo'
-
-If you define all your C<PLUGINS> with lower case names then they will be
-located regardless of how the user specifies the name in the USE
-directive. If, on the other hand, you define your C<PLUGINS> with upper
-or mixed case names then the name specified in the C<USE> directive must
-match the case exactly.
-
-The C<USE> directive is used to create plugin objects and does so by calling
-the L<plugin()|Template::Context#plugin()> method on the current
-L<Template::Context> object. If the plugin name is defined in the C<PLUGINS>
-hash then the corresponding Perl module is loaded via C<require()>. The
-context then calls the L<load()|Template::Plugin#load()> class method which
-should return the class name (default and general case) or a prototype object
-against which the L<new()|Template::Plugin#new()> method can be called to
-instantiate individual plugin objects.
-
-If the plugin name is not defined in the C<PLUGINS> hash then the
-C<PLUGIN_BASE> and/or C<LOAD_PERL> options come into effect.
-
-=head2 PLUGIN_BASE
-
-If a plugin is not defined in the C<PLUGINS> hash then the C<PLUGIN_BASE> is used
-to attempt to construct a correct Perl module name which can be successfully
-loaded.
-
-The C<PLUGIN_BASE> can be specified as a reference to an array of module
-namespaces, or as a single value which is automatically converted to a
-list. The default C<PLUGIN_BASE> value (C<Template::Plugin>) is then added
-to the end of this list.
-
-example 1:
-
- my $template = Template->new({
- PLUGIN_BASE => 'MyOrg::Template::Plugin',
- });
-
- [% USE Foo %] # => MyOrg::Template::Plugin::Foo
- or Template::Plugin::Foo
-
-example 2:
-
- my $template = Template->new({
- PLUGIN_BASE => [ 'MyOrg::Template::Plugin',
- 'YourOrg::Template::Plugin' ],
- });
-
-template:
-
- [% USE Foo %] # => MyOrg::Template::Plugin::Foo
- or YourOrg::Template::Plugin::Foo
- or Template::Plugin::Foo
-
-If you don't want the default C<Template::Plugin> namespace added to the
-end of the C<PLUGIN_BASE>, then set the C<$Template::Plugins::PLUGIN_BASE>
-variable to a false value before calling the L<new()|Template> L<Template#new()>
-constructor method. This is shown in the example below where the
-C<Foo> plugin is located as C<My::Plugin::Foo> or C<Your::Plugin::Foo> but not
-as C<Template::Plugin::Foo>.
-
-example 3:
-
- use Template::Plugins;
- $Template::Plugins::PLUGIN_BASE = '';
-
- my $template = Template->new({
- PLUGIN_BASE => [ 'My::Plugin',
- 'Your::Plugin' ],
- });
-
-template:
-
- [% USE Foo %] # => My::Plugin::Foo
- or Your::Plugin::Foo
-
-=head2 LOAD_PERL
-
-If a plugin cannot be loaded using the C<PLUGINS> or C<PLUGIN_BASE>
-approaches then the provider can make a final attempt to load the
-module without prepending any prefix to the module path. This allows
-regular Perl modules (i.e. those that don't reside in the
-L<Template::Plugin> or some other such namespace) to be loaded and used
-as plugins.
-
-By default, the C<LOAD_PERL> option is set to C<0> and no attempt will be made
-to load any Perl modules that aren't named explicitly in the C<PLUGINS>
-hash or reside in a package as named by one of the C<PLUGIN_BASE>
-components.
-
-Plugins loaded using the C<PLUGINS> or C<PLUGIN_BASE> receive a reference to
-the current context object as the first argument to the
-L<new()|Template::Plugin#new()> constructor. Modules loaded using C<LOAD_PERL>
-are assumed to not conform to the plugin interface. They must provide a C<new()>
-class method for instantiating objects but it will not receive a reference to
-the context as the first argument.
-
-Plugin modules should provide a L<load()|Template::Plugin#load()> class method
-(or inherit the default one from the L<Template::Plugin> base class) which is
-called the first time the plugin is loaded. Regular Perl modules need not. In
-all other respects, regular Perl objects and Template Toolkit plugins are
-identical.
-
-If a particular Perl module does not conform to the common, but not
-unilateral, C<new()> constructor convention then a simple plugin wrapper
-can be written to interface to it.
-
-=head2 FILTERS
-
-The C<FILTERS> option can be used to specify custom filters which can
-then be used with the C<FILTER> directive like any other. These are
-added to the standard filters which are available by default. Filters
-specified via this option will mask any standard filters of the same
-name.
-
-The C<FILTERS> option should be specified as a reference to a hash array
-in which each key represents the name of a filter. The corresponding
-value should contain a reference to an array containing a subroutine
-reference and a flag which indicates if the filter is static (C<0>) or
-dynamic (C<1>). A filter may also be specified as a solitary subroutine
-reference and is assumed to be static.
-
- $template = Template->new({
- FILTERS => {
- 'sfilt1' => \&static_filter, # static
- 'sfilt2' => [ \&static_filter, 0 ], # same as above
- 'dfilt1' => [ \&dyanamic_filter_factory, 1 ],
- },
- });
-
-Additional filters can be specified at any time by calling the
-L<define_filter()|Template::Context#define_filter()> method on the current
-L<Template::Context> object. The method accepts a filter name, a reference to a
-filter subroutine and an optional flag to indicate if the filter is dynamic.
-
- my $context = $template->context();
- $context->define_filter('new_html', \&new_html);
- $context->define_filter('new_repeat', \&new_repeat, 1);
-
-Static filters are those where a single subroutine reference is used
-for all invocations of a particular filter. Filters that don't accept
-any configuration parameters (e.g. C<html>) can be implemented
-statically. The subroutine reference is simply returned when that
-particular filter is requested. The subroutine is called to filter
-the output of a template block which is passed as the only argument.
-The subroutine should return the modified text.
-
- sub static_filter {
- my $text = shift;
- # do something to modify $text...
- return $text;
- }
-
-The following template fragment:
-
- [% FILTER sfilt1 %]
- Blah blah blah.
- [% END %]
-
-is approximately equivalent to:
-
- &static_filter("\nBlah blah blah.\n");
-
-Filters that can accept parameters (e.g. C<truncate>) should be
-implemented dynamically. In this case, the subroutine is taken to be
-a filter 'factory' that is called to create a unique filter subroutine
-each time one is requested. A reference to the current
-L<Template::Context> object is passed as the first parameter, followed by
-any additional parameters specified. The subroutine should return
-another subroutine reference (usually a closure) which implements the
-filter.
-
- sub dynamic_filter_factory {
- my ($context, @args) = @_;
-
- return sub {
- my $text = shift;
- # do something to modify $text...
- return $text;
- }
- }
-
-The following template fragment:
-
- [% FILTER dfilt1(123, 456) %]
- Blah blah blah
- [% END %]
-
-is approximately equivalent to:
-
- my $filter = &dynamic_filter_factory($context, 123, 456);
- &$filter("\nBlah blah blah.\n");
-
-See the C<FILTER> directive for further examples.
-
-=head1 Customisation and Extension
-
-=head2 LOAD_TEMPLATES
-
-The C<LOAD_TEMPLATES> option can be used to provide a reference to a list
-of L<Template::Provider> objects or sub-classes thereof which will take
-responsibility for loading and compiling templates.
-
- my $template = Template->new({
- LOAD_TEMPLATES => [
- MyOrg::Template::Provider->new({ ... }),
- Template::Provider->new({ ... }),
- ],
- });
-
-When a C<PROCESS>, C<INCLUDE> or C<WRAPPER> directive is encountered, the
-named template may refer to a locally defined C<BLOCK> or a file relative to
-the C<INCLUDE_PATH> (or an absolute or relative path if the appropriate
-C<ABSOLUTE> or C<RELATIVE> options are set). If a C<BLOCK> definition can't be
-found (see the L<Template::Context> L<template()|Template::Context#template()>
-method for a discussion of C<BLOCK> locality) then each of the
-C<LOAD_TEMPLATES> provider objects is queried in turn via the
-L<fetch()|Template::Provider#fetch()> method to see if it can supply the
-required template.
-
-Each provider can return a compiled template, an error, or decline to service
-the request in which case the responsibility is passed to the next provider.
-If none of the providers can service the request then a 'not found' error is
-returned. The same basic provider mechanism is also used for the C<INSERT>
-directive but it bypasses any C<BLOCK> definitions and doesn't attempt is to
-parse or process the contents of the template file.
-
-If C<LOAD_TEMPLATES> is undefined, a single default provider will be
-instantiated using the current configuration parameters. For example, the
-L<Template::Provider> C<INCLUDE_PATH> option can be specified in the L<Template>
-configuration and will be correctly passed to the provider's constructor
-method.
-
- my $template = Template->new({
- INCLUDE_PATH => '/here:/there',
- });
-
-=head2 LOAD_PLUGINS
-
-The C<LOAD_PLUGINS> options can be used to specify a list of provider objects
-(i.e. they implement the L<fetch()|Template::Plugins#fetch()> method) which
-are responsible for loading and instantiating template plugin objects. The
-L<Template::Context> L<plugin()|Template::Context#plugin()> method queries
-each provider in turn in a "Chain of Responsibility" as per the
-L<template()|Template::Context#template()> and
-L<filter()|Template::Context#filter()> methods.
-
- my $template = Template->new({
- LOAD_PLUGINS => [
- MyOrg::Template::Plugins->new({ ... }),
- Template::Plugins->new({ ... }),
- ],
- });
-
-By default, a single L<Template::Plugins> object is created using the
-current configuration hash. Configuration items destined for the
-L<Template::Plugins> constructor may be added to the Template
-constructor.
-
- my $template = Template->new({
- PLUGIN_BASE => 'MyOrg::Template::Plugins',
- LOAD_PERL => 1,
- });
-
-=head2 LOAD_FILTERS
-
-The C<LOAD_FILTERS> option can be used to specify a list of provider objects
-(i.e. they implement the L<fetch()|Template::Filters#fetch()> method) which
-are responsible for returning and/or creating filter subroutines. The
-L<Template::Context> L<filter()|Template::Context#filter()> method queries
-each provider in turn in a "Chain of Responsibility" as per the
-L<template()|Template::Context#template()> and
-L<plugin()|Template::Context#plugin()> methods.
-
- my $template = Template->new({
- LOAD_FILTERS => [
- MyTemplate::Filters->new(),
- Template::Filters->new(),
- ],
- });
-
-By default, a single L<Template::Filters> object is created for the
-C<LOAD_FILTERS> list.
-
-=head2 TOLERANT
-
-The C<TOLERANT> flag is used by the various Template Toolkit provider modules
-(L<Template::Provider>, L<Template::Plugins>, L<Template::Filters>) to control
-their behaviour when errors are encountered. By default, any errors are
-reported as such, with the request for the particular resource (C<template>,
-C<plugin>, C<filter>) being denied and an exception raised.
-
-When the C<TOLERANT> flag is set to any true values, errors will be silently
-ignored and the provider will instead return C<STATUS_DECLINED>. This allows a
-subsequent provider to take responsibility for providing the resource, rather
-than failing the request outright. If all providers decline to service the
-request, either through tolerated failure or a genuine disinclination to
-comply, then a 'C<E<lt>resourceE<gt> not found>' exception is raised.
-
-=head2 SERVICE
-
-A reference to a L<Template::Service> object, or sub-class thereof, to which
-the L<Template> module should delegate. If unspecified, a L<Template::Service>
-object is automatically created using the current configuration hash.
-
- my $template = Template->new({
- SERVICE => MyOrg::Template::Service->new({ ... }),
- });
-
-=head2 CONTEXT
-
-A reference to a L<Template::Context> object which is used to define a
-specific environment in which template are processed. A L<Template::Context>
-object is passed as the only parameter to the Perl subroutines that represent
-"compiled" template documents. Template subroutines make callbacks into the
-context object to access Template Toolkit functionality, for example, to
-C<INCLUDE> or C<PROCESS> another template
-(L<include()|Template::Context#include()> and
-L<process()|Template::Context#process()> methods, respectively), to C<USE> a
-plugin (L<plugin()|Template::Context#plugin()>) or instantiate a filter
-(L<filter()|Template::Context#filter()>) or to access the stash
-(L<stash()|Template::Context#stash()>) which manages variable definitions via
-the L<get()|Template::Stash#get()> and L<set()|Template::Stash#set()> methods.
-
- my $template = Template->new({
- CONTEXT => MyOrg::Template::Context->new({ ... }),
- });
-
-=head2 STASH
-
-A reference to a L<Template::Stash> object or sub-class which will take
-responsibility for managing template variables.
-
- my $stash = MyOrg::Template::Stash->new({ ... });
- my $template = Template->new({
- STASH => $stash,
- });
-
-If unspecified, a default stash object is created using the C<VARIABLES>
-configuration item to initialise the stash variables.
-
- my $template = Template->new({
- VARIABLES => {
- id => 'abw',
- name => 'Andy Wardley',
- },
- };
-
-=head2 PARSER
-
-The L<Template::Parser> module implements a parser object for compiling
-templates into Perl code which can then be executed. A default object
-of this class is created automatically and then used by the
-L<Template::Provider> whenever a template is loaded and requires
-compilation. The C<PARSER> option can be used to provide a reference to
-an alternate parser object.
-
- my $template = Template->new({
- PARSER => MyOrg::Template::Parser->new({ ... }),
- });
-
-=head2 GRAMMAR
-
-The C<GRAMMAR> configuration item can be used to specify an alternate
-grammar for the parser. This allows a modified or entirely new
-template language to be constructed and used by the Template Toolkit.
-
-Source templates are compiled to Perl code by the L<Template::Parser>
-using the L<Template::Grammar> (by default) to define the language
-structure and semantics. Compiled templates are thus inherently
-"compatible" with each other and there is nothing to prevent any
-number of different template languages being compiled and used within
-the same Template Toolkit processing environment (other than the usual
-time and memory constraints).
-
-The L<Template::Grammar> file is constructed from a YACC like grammar
-(using C<Parse::YAPP>) and a skeleton module template. These files are
-provided, along with a small script to rebuild the grammar, in the
-F<parser> sub-directory of the distribution.
-
-You don't have to know or worry about these unless you want to hack on the
-template language or define your own variant. There is a F<README> file in the
-same directory which provides some small guidance but it is assumed that you
-know what you're doing if you venture herein. If you grok LALR parsers, then
-you should find it comfortably familiar.
-
-By default, an instance of the default L<Template::Grammar> will be
-created and used automatically if a C<GRAMMAR> item isn't specified.
-
- use MyOrg::Template::Grammar;
-
- my $template = Template->new({
- GRAMMAR = MyOrg::Template::Grammar->new();
- });
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Credits
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2014 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=encoding utf8
-
-=head1 NAME
-
-Template::Manual::Credits - Author and contributor credits
-
-=head1 HISTORY
-
-The Template Toolkit began its life as the C<Text::MetaText> module,
-originally released to CPAN around 1996. This itself was the public
-manifestation of an earlier template processing system I developed
-while working at Peritas (now Knowledge Pool -
-http://www.knowledgepool.com/)
-
-C<Text::MetaText> was the prototype - the one we always planned to throw
-away. It did the job well, showing us what worked and what didn't, what
-was good and what was bad, and gave us some ideas about what could be
-done better, given the chance to start again from scratch.
-
-Some time late in 1998 I threw away the prototype and started work on the
-Template Toolkit. By then I was working at Canon Research Centre Europe Ltd.
-(CRE), involved in a general research programme related to web publishing and
-dynamic content generation. The first alpha release was in June 1999, followed
-by numerous more alpha and beta releases culminating in 1.00 being released on
-2nd December 1999.
-
-A month or so later, work had begun on version 2.00. The plan was to get the
-template language relatively stable in version 1.00 and not worry too much
-about performance or other internal matters. Then, version 2.00 would follow
-to improve performance, clean up the architecture and fix anything that, with
-the benefit of hindsight, we thought could be improved. As it happens, me
-starting work on version 2.00 coincided with Doug Steinwand sending me his
-parser variant which compiled templates to Perl code, giving a major
-performance boost. As well as the speedups, there are a whole host of
-significant new features in version 2.00, and a greatly improved internal
-architecture. Apart from a few minor "fixups" the template directives and
-language have remained the same as in version 1.00
-
-Version 2.00 was available in beta release form in July 2000, just in time for
-the 4th Perl Conference where version 1.00 was awarded "Best New Perl Module".
-After another extended beta release period, version 2.00 was released on 1st
-December 2000.
-
-Version 3 has been in development ever since.
-
-=head1 AUTHOR
-
-Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
-
-=head1 COPYRIGHT
-
-Copyright (C) 1996-2014 Andy Wardley. All Rights Reserved.
-
-The Template Toolkit is free software; you can redistribute it and/or
-modify it under the same terms as Perl itself.
-
-=head1 CONTRIBUTORS
-
-Many people have contributed ideas, inspiration, fixes and features to
-the Template Toolkit. Their efforts continue to be very much appreciated.
-Please let me know if you think anyone is missing from this list.
-
-If you submit a patch/pull request then please make sure you add your
-own name to this list and include it in the changes.
-
-Amiri Barksdale, Thierry-Michel Barral, Craig Barratt, Stas Bekman, Robin Berjon,
-Tony Bowden, Neil Bowers, Leon Brocard, Lyle Brooks, Norbert Buchmüller,
-Dave Cash, Piers Cawley, Darren Chamberlain, Timmy Chan, Eric Cholet, Chromatic,
-Nik Clayton, Tosh Cooey, Dave Cross, Chris Dean, Francois Desarmenien, Horst Dumcke,
-Mark Fowler, Michael Fowler, Brian Fraser, Kenny Gatdula, Axel Gerstmair, Jay Hannah, Dylan
-William Hardison, Perrin Harkins, Bryce Harrington, Dave Hodgkinson, Lubomir
-Host, Dave Howorth, Jon Jensen, Harald Joerg, Colin Johnson, Colin Keith,
-Adam Kennedy, Vivek Khera, Alexey A. Kiritchun, Rafael Kitover, Andreas
-Koenig, Ivan Kurmanov, Denis F. Latypoff, Hans von Lengerke, Jonas Liljegren,
-Simon Napiorkowski, Breno G. de Oliveira, Leslie Michael Orchard, Paul Orrock,
-Jonathon Padfield, Steve Peters, Briac PilprE<eacute>, Yuri Pimenov, Martin
-Portman, Marc Remy, Slaven Rezic, Jess Robinson, Josh Rosenbaum, Christian
-Schaffner, Mike Schilli, Randal L. Schwartz, Paul Seamons, Paul Sharpe,
-Ricardo Signes, Ville SkyttE<auml>, Barrie Slaymaker, David Steinbrunner, Doug
-Steinwand, Michael Stevens, Autrijus Tang, Drew Taylor, Rod Taylor, Swen
-Thuemmler, Richard Tietjen, Ben Tilly, Stathy G. Touloumis, Jim Vaughan, Simon
-Wilcox, Chris Winters.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Directives
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Directives - Template directives
-
-=head1 Accessing and Updating Template Variables
-
-=head2 GET
-
-The C<GET> directive retrieves and outputs the value of the named variable.
-
- [% GET foo %]
-
-The C<GET> keyword is optional. A variable can be specified in a directive
-tag by itself.
-
- [% foo %]
-
-The variable can have an unlimited number of elements, each separated by a
-dot. Each element can have arguments specified within parentheses.
-
- [% foo %]
- [% bar.baz %]
- [% biz.baz(10) %]
- ...etc...
-
-See L<Template::Manual::Variables> for a full discussion on template
-variables.
-
-You can also specify expressions using the logical (C<and>, C<or>, C<not>, C<?>, C<:>) and
-mathematic operators (C<+>, C<->, C<*>, C</>, C<%>, C<mod>, C<div>).
-
- [% template.title or default.title %]
-
- [% score * 100 %]
-
- [% order.nitems ? checkout(order.total) : 'no items' %]
-
-The C<div> operator returns the integer result of division. Both C<%> and
-C<mod> return the modulus (i.e. remainder) of division.
-
- [% 15 / 6 %] # 2.5
- [% 15 div 6 %] # 2
- [% 15 mod 6 %] # 3
-
-=head2 CALL
-
-The C<CALL> directive is similar to C<GET> in evaluating the variable named,
-but doesn't print the result returned. This can be useful when a
-variable is bound to a sub-routine or object method which you want to
-call but aren't interested in the value returned.
-
- [% CALL dbi.disconnect %]
-
- [% CALL inc_page_counter(page_count) %]
-
-=head2 SET
-
-The C<SET> directive allows you to assign new values to existing variables
-or create new temporary variables.
-
- [% SET title = 'Hello World' %]
-
-The C<SET> keyword is also optional.
-
- [% title = 'Hello World' %]
-
-Variables may be assigned the values of other variables, unquoted
-numbers (2.718), literal text ('single quotes') or quoted text
-("double quotes"). In the latter case, any variable references within
-the text will be interpolated when the string is evaluated. Variables
-should be prefixed by C<$>, using curly braces to explicitly scope
-the variable name where necessary.
-
- [% foo = 'Foo' %] # literal value 'Foo'
- [% bar = foo %] # value of variable 'foo'
- [% cost = '$100' %] # literal value '$100'
- [% item = "$bar: ${cost}.00" %] # value "Foo: $100.00"
-
-Multiple variables may be assigned in the same directive and are
-evaluated in the order specified. Thus, the above could have been
-written:
-
- [% foo = 'Foo'
- bar = foo
- cost = '$100'
- item = "$bar: ${cost}.00"
- %]
-
-Simple expressions can also be used, as per C<GET>.
-
- [% ten = 10
- twenty = 20
- thirty = twenty + ten
- forty = 2 * twenty
- fifty = 100 div 2
- six = twenty mod 7
- %]
-
-You can concatenate strings together using the C<' _ '> operator. In Perl 5,
-the C<.> is used for string concatenation, but in Perl 6, as in the Template
-Toolkit, the C<.> will be used as the method calling operator and C<' _ '> will
-be used for string concatenation. Note that the operator must be
-specified with surrounding whitespace which, as Larry says, is construed as
-a feature:
-
- [% copyright = '(C) Copyright' _ year _ ' ' _ author %]
-
-You can, of course, achieve a similar effect with double quoted string
-interpolation.
-
- [% copyright = "(C) Copyright $year $author" %]
-
-=head2 DEFAULT
-
-The C<DEFAULT> directive is similar to C<SET> but only updates variables
-that are currently undefined or have no "true" value (in the Perl
-sense).
-
- [% DEFAULT
- name = 'John Doe'
- id = 'jdoe'
- %]
-
-This can be particularly useful in common template components to
-ensure that some sensible default are provided for otherwise
-undefined variables.
-
- [% DEFAULT
- title = 'Hello World'
- bgcol = '#ffffff'
- %]
- <html>
- <head>
- <title>[% title %]</title>
- </head>
- <body bgcolor="[% bgcol %]">
- ...etc...
-
-=head1 Processing Template Files and Blocks
-
-=head2 INSERT
-
-The C<INSERT> directive is used to insert the contents of an external file
-at the current position.
-
- [% INSERT myfile %]
-
-No attempt to parse or process the file is made. The contents,
-possibly including any embedded template directives, are inserted
-intact.
-
-The filename specified should be relative to one of the C<INCLUDE_PATH>
-directories. Absolute (i.e. starting with C</>) and relative
-(i.e. starting with C<.>) filenames may be used if the C<ABSOLUTE> and
-C<RELATIVE> options are set, respectively. Both these options are
-disabled by default.
-
- my $template = Template->new({
- INCLUDE_PATH => '/here:/there',
- });
-
- $template->process('myfile');
-
-F<myfile>:
-
- [% INSERT foo %] # looks for /here/foo then /there/foo
- [% INSERT /etc/passwd %] # file error: ABSOLUTE not set
- [% INSERT ../secret %] # file error: RELATIVE not set
-
-For convenience, the filename does not need to be quoted as long as it
-contains only alphanumeric characters, underscores, dots or forward
-slashes. Names containing any other characters should be quoted.
-
- [% INSERT misc/legalese.txt %]
- [% INSERT 'dos98/Program Files/stupid' %]
-
-To evaluate a variable to specify a filename, you should explicitly
-prefix it with a C<$> or use double-quoted string interpolation.
-
- [% language = 'en'
- legalese = 'misc/legalese.txt'
- %]
-
- [% INSERT $legalese %] # misc/legalese.txt
- [% INSERT "$language/$legalese" %] # en/misc/legalese.txt
-
-Multiple files can be specified using C<+> as a delimiter. All files
-should be unquoted names or quoted strings. Any variables should be
-interpolated into double-quoted strings.
-
- [% INSERT legalese.txt + warning.txt %]
- [% INSERT "$legalese" + warning.txt %] # requires quoting
-
-=head2 INCLUDE
-
-The C<INCLUDE> directive is used to process and include the output of
-another template file or block.
-
- [% INCLUDE header %]
-
-If a C<BLOCK> of the specified name is defined in the same file, or in a file
-from which the current template has been called (i.e. a parent template) then
-it will be used in preference to any file of the same name.
-
- [% INCLUDE table %] # uses BLOCK defined below
-
- [% BLOCK table %]
- <table>
- ...
- </table>
- [% END %]
-
-If a C<BLOCK> definition is not currently visible then the template name
-should be a file relative to one of the C<INCLUDE_PATH> directories, or
-an absolute or relative file name if the C<ABSOLUTE>/C<RELATIVE> options are
-appropriately enabled. The C<INCLUDE> directive automatically quotes the
-filename specified, as per C<INSERT> described above. When a variable
-contains the name of the template for the C<INCLUDE> directive, it should
-be explicitly prefixed by C<$> or double-quoted
-
- [% myheader = 'my/misc/header' %]
- [% INCLUDE myheader %] # 'myheader'
- [% INCLUDE $myheader %] # 'my/misc/header'
- [% INCLUDE "$myheader" %] # 'my/misc/header'
-
-Any template directives embedded within the file will be processed
-accordingly. All variables currently defined will be visible and
-accessible from within the included template.
-
- [% title = 'Hello World' %]
- [% INCLUDE header %]
- <body>
- ...
-
-F<header>:
-
- <html>
- <title>[% title %]</title>
-
-output:
-
- <html>
- <title>Hello World</title>
- <body>
- ...
-
-Local variable definitions may be specified after the template name,
-temporarily masking any existing variables. Insignificant whitespace
-is ignored within directives so you can add variable definitions on the
-same line, the next line or split across several line with comments
-interspersed, if you prefer.
-
- [% INCLUDE table %]
-
- [% INCLUDE table title="Active Projects" %]
-
- [% INCLUDE table
- title = "Active Projects"
- bgcolor = "#80ff00" # chartreuse
- border = 2
- %]
-
-The C<INCLUDE> directive localises (i.e. copies) all variables before
-processing the template. Any changes made within the included
-template will not affect variables in the including template.
-
- [% foo = 10 %]
-
- foo is originally [% foo %]
- [% INCLUDE bar %]
- foo is still [% foo %]
-
- [% BLOCK bar %]
- foo was [% foo %]
- [% foo = 20 %]
- foo is now [% foo %]
- [% END %]
-
-output:
-
- foo is originally 10
- foo was 10
- foo is now 20
- foo is still 10
-
-Technical Note: the localisation of the stash (that is, the process by
-which variables are copied before an C<INCLUDE> to prevent being
-overwritten) is only skin deep. The top-level variable namespace
-(hash) is copied, but no attempt is made to perform a deep-copy of
-other structures (hashes, arrays, objects, etc.) Therefore, a C<foo>
-variable referencing a hash will be copied to create a new C<foo>
-variable but which points to the same hash array. Thus, if you update
-compound variables (e.g. C<foo.bar>) then you will change the original
-copy, regardless of any stash localisation. If you're not worried
-about preserving variable values, or you trust the templates you're
-including then you might prefer to use the C<PROCESS> directive which is
-faster by virtue of not performing any localisation.
-
-You can specify dotted variables as "local" variables to an C<INCLUDE> directive.
-However, be aware that because of the localisation issues explained above (if
-you skipped the previous Technical Note above then you might want to go back
-and read it or skip this section too), the variables might not actually be
-"local". If the first element of the variable name already references a hash
-array then the variable update will affect the original variable.
-
- [% foo = {
- bar = 'Baz'
- }
- %]
-
- [% INCLUDE somefile foo.bar='Boz' %]
-
- [% foo.bar %] # Boz
-
-This behaviour can be a little unpredictable (and may well be improved
-upon in a future version). If you know what you're doing with it and
-you're sure that the variables in question are defined (nor not) as you
-expect them to be, then you can rely on this feature to implement some
-powerful "global" data sharing techniques. Otherwise, you might prefer
-to steer well clear and always pass simple (undotted) variables as
-parameters to C<INCLUDE> and other similar directives.
-
-If you want to process several templates in one go then you can
-specify each of their names (quoted or unquoted names only, no unquoted
-C<$variables>) joined together by C<+>. The C<INCLUDE> directive
-will then process them in order.
-
- [% INCLUDE html/header + "site/$header" + site/menu
- title = "My Groovy Web Site"
- %]
-
-The variable stash is localised once and then the templates specified
-are processed in order, all within that same variable context. This
-makes it slightly faster than specifying several separate C<INCLUDE>
-directives (because you only clone the variable stash once instead of
-n times), but not quite as "safe" because any variable changes in the
-first file will be visible in the second, third and so on. This
-might be what you want, of course, but then again, it might not.
-
-=head2 PROCESS
-
-The PROCESS directive is similar to C<INCLUDE> but does not perform any
-localisation of variables before processing the template. Any changes
-made to variables within the included template will be visible in the
-including template.
-
- [% foo = 10 %]
-
- foo is [% foo %]
- [% PROCESS bar %]
- foo is [% foo %]
-
- [% BLOCK bar %]
- [% foo = 20 %]
- changed foo to [% foo %]
- [% END %]
-
-output:
-
- foo is 10
- changed foo to 20
- foo is 20
-
-Parameters may be specified in the C<PROCESS> directive, but these too will
-become visible changes to current variable values.
-
- [% foo = 10 %]
- foo is [% foo %]
- [% PROCESS bar
- foo = 20
- %]
- foo is [% foo %]
-
- [% BLOCK bar %]
- this is bar, foo is [% foo %]
- [% END %]
-
-output:
-
- foo is 10
- this is bar, foo is 20
- foo is 20
-
-The C<PROCESS> directive is slightly faster than C<INCLUDE> because it
-avoids the need to localise (i.e. copy) the variable stash before
-processing the template. As with C<INSERT> and C<INCLUDE>, the first
-parameter does not need to be quoted as long as it contains only
-alphanumeric characters, underscores, periods or forward slashes.
-A C<$> prefix can be used to explicitly indicate a variable which
-should be interpolated to provide the template name:
-
- [% myheader = 'my/misc/header' %]
- [% PROCESS myheader %] # 'myheader'
- [% PROCESS $myheader %] # 'my/misc/header'
-
-As with C<INCLUDE>, multiple templates can be specified, delimited by
-C<+>, and are processed in order.
-
- [% PROCESS html/header + my/header %]
-
-=head2 WRAPPER
-
-It's not unusual to find yourself adding common headers and footers to
-pages or sub-sections within a page. Something like this:
-
- [% INCLUDE section/header
- title = 'Quantum Mechanics'
- %]
- Quantum mechanics is a very interesting subject wish
- should prove easy for the layman to fully comprehend.
- [% INCLUDE section/footer %]
-
- [% INCLUDE section/header
- title = 'Desktop Nuclear Fusion for under $50'
- %]
- This describes a simple device which generates significant
- sustainable electrical power from common tap water by process
- of nuclear fusion.
- [% INCLUDE section/footer %]
-
-The individual template components being included might look like these:
-
-section/header:
-
- <p>
- <h2>[% title %]</h2>
-
-section/footer:
-
- </p>
-
-The C<WRAPPER> directive provides a way of simplifying this a little. It
-encloses a block up to a matching C<END> directive, which is first processed
-to generate some output. This is then passed to the named template file or
-C<BLOCK> as the C<content> variable.
-
- [% WRAPPER section
- title = 'Quantum Mechanics'
- %]
- Quantum mechanics is a very interesting subject wish
- should prove easy for the layman to fully comprehend.
- [% END %]
-
- [% WRAPPER section
- title = 'Desktop Nuclear Fusion for under $50'
- %]
- This describes a simple device which generates significant
- sustainable electrical power from common tap water by process
- of nuclear fusion.
- [% END %]
-
-The single 'section' template can then be defined as:
-
- <h2>[% title %]</h2>
- <p>
- [% content %]
- </p>
-
-Like other block directives, it can be used in side-effect notation:
-
- [% INSERT legalese.txt WRAPPER big_bold_table %]
-
-It's also possible to specify multiple templates to a C<WRAPPER> directive.
-The specification order indicates outermost to innermost wrapper templates.
-For example, given the following template block definitions:
-
- [% BLOCK bold %]<b>[% content %]</b>[% END %]
- [% BLOCK italic %]<i>[% content %]</i>[% END %]
-
-the directive
-
- [% WRAPPER bold+italic %]Hello World[% END %]
-
-would generate the following output:
-
- <b><i>Hello World</i></b>
-
-=head2 BLOCK
-
-The C<BLOCK>...C<END> construct can be used to define template component
-blocks which can be processed with the C<INCLUDE>, C<PROCESS> and C<WRAPPER>
-directives.
-
- [% BLOCK tabrow %]
- <tr>
- <td>[% name %]<td>
- <td>[% email %]</td>
- </tr>
- [% END %]
-
- <table>
- [% PROCESS tabrow name='Fred' email='fred@nowhere.com' %]
- [% PROCESS tabrow name='Alan' email='alan@nowhere.com' %]
- </table>
-
-A C<BLOCK> definition can be used before it is defined, as long as the
-definition resides in the same file. The block definition itself does
-not generate any output.
-
- [% PROCESS tmpblk %]
-
- [% BLOCK tmpblk %] This is OK [% END %]
-
-You can use an anonymous C<BLOCK> to capture the output of a template
-fragment.
-
- [% julius = BLOCK %]
- And Caesar's spirit, ranging for revenge,
- With Ate by his side come hot from hell,
- Shall in these confines with a monarch's voice
- Cry 'Havoc', and let slip the dogs of war;
- That this foul deed shall smell above the earth
- With carrion men, groaning for burial.
- [% END %]
-
-Like a named block, it can contain any other template directives which
-are processed when the block is defined. The output generated by the
-block is then assigned to the variable C<julius>.
-
-Anonymous C<BLOCK>s can also be used to define block macros. The
-enclosing block is processed each time the macro is called.
-
- [% MACRO locate BLOCK %]
- The [% animal %] sat on the [% place %].
- [% END %]
-
- [% locate(animal='cat', place='mat') %] # The cat sat on the mat
- [% locate(animal='dog', place='log') %] # The dog sat on the log
-
-=head1 Conditional Processing
-
-=head2 IF / UNLESS / ELSIF / ELSE
-
-The C<IF> and C<UNLESS> directives can be used to process or ignore a
-block based on some run-time condition.
-
- [% IF frames %]
- [% INCLUDE frameset %]
- [% END %]
-
- [% UNLESS text_mode %]
- [% INCLUDE biglogo %]
- [% END %]
-
-Multiple conditions may be joined with C<ELSIF> and/or C<ELSE> blocks.
-
- [% IF age < 10 %]
- Hello [% name %], does your mother know you're
- using her AOL account?
- [% ELSIF age < 18 %]
- Sorry, you're not old enough to enter
- (and too dumb to lie about your age)
- [% ELSE %]
- Welcome [% name %].
- [% END %]
-
-The following conditional and boolean operators may be used:
-
- == != < <= > >= && || ! and or not
-
-Conditions may be arbitrarily complex and are evaluated with the same
-precedence as in Perl. Parenthesis may be used to explicitly
-determine evaluation order.
-
- # ridiculously contrived complex example
- [% IF (name == 'admin' || uid <= 0) && mode == 'debug' %]
- I'm confused.
- [% ELSIF more > less %]
- That's more or less correct.
- [% END %]
-
-The C<and>, C<or> and C<not> operator are provided as aliases for
-C<&&>, C<||> and C<!>, respectively. Unlike Perl, which treats
-C<and>, C<or> and C<not> as separate, lower-precedence versions of the
-other operators, the Template Toolkit performs a straightforward substitution
-of C<and> for C<&&>, and so on. That means that C<and>, C<or> and C<not>
-have the same operator precedence as C<&&>, C<||> and C<!>.
-
-=head2 SWITCH / CASE
-
-The C<SWITCH> / C<CASE> construct can be used to perform a multi-way
-conditional test. The C<SWITCH> directive expects an expression which is
-first evaluated and then compared against each CASE statement in turn.
-Each C<CASE> directive should contain a single value or a list of values
-which should match. C<CASE> may also be left blank or written as
-C<[% CASE DEFAULT %]> to specify a default match. Only one C<CASE> matches,
-there is no drop-through between C<CASE> statements.
-
- [% SWITCH myvar %]
- [% CASE 'value1' %]
- ...
- [% CASE ['value2', 'value3'] %] # multiple values
- ...
- [% CASE myhash.keys %] # ditto
- ...
- [% CASE %] # default
- ...
- [% END %]
-
-=head1 Loop Processing
-
-=head2 FOREACH
-
-The C<FOREACH> directive will iterate through the items in a list, processing
-the enclosed block for each one.
-
- [% foo = 'Foo'
- items = [ 'one', 'two', 'three' ]
- %]
-
- Things:
- [% FOREACH thing IN [ foo 'Bar' "$foo Baz" ] %]
- * [% thing %]
- [% END %]
-
- Items:
- [% FOREACH i IN items %]
- * [% i %]
- [% END %]
-
- Stuff:
- [% stuff = [ foo "$foo Bar" ] %]
- [% FOREACH s IN stuff %]
- * [% s %]
- [% END %]
-
-output:
-
- Things:
- * Foo
- * Bar
- * Foo Baz
-
- Items:
- * one
- * two
- * three
-
- Stuff:
- * Foo
- * Foo Bar
-
-You can use also use C<=> instead of C<IN> if you prefer.
-
- [% FOREACH i = items %]
-
-When the C<FOREACH> directive is used without specifying a target variable,
-any iterated values which are hash references will be automatically
-imported.
-
- [% userlist = [
- { id => 'tom', name => 'Thomas' },
- { id => 'dick', name => 'Richard' },
- { id => 'larry', name => 'Lawrence' },
- ]
- %]
-
- [% FOREACH user IN userlist %]
- [% user.id %] [% user.name %]
- [% END %]
-
-short form:
-
- [% FOREACH userlist %]
- [% id %] [% name %]
- [% END %]
-
-Note that this particular usage creates a localised variable context
-to prevent the imported hash keys from overwriting any existing
-variables. The imported definitions and any other variables defined
-in such a C<FOREACH> loop will be lost at the end of the loop, when the
-previous context and variable values are restored.
-
-However, under normal operation, the loop variable remains in scope
-after the C<FOREACH> loop has ended (caveat: overwriting any variable
-previously in scope). This is useful as the loop variable is secretly
-an iterator object (see below) and can be used to analyse the last
-entry processed by the loop.
-
-The C<FOREACH> directive can also be used to iterate through the entries
-in a hash array. Each entry in the hash is returned in sorted order
-(based on the key) as a hash array containing 'key' and 'value' items.
-
- [% users = {
- tom => 'Thomas',
- dick => 'Richard',
- larry => 'Lawrence',
- }
- %]
-
- [% FOREACH u IN users %]
- * [% u.key %] : [% u.value %]
- [% END %]
-
-Output:
-
- * dick : Richard
- * larry : Lawrence
- * tom : Thomas
-
-The C<NEXT> directive starts the next iteration in the C<FOREACH> loop.
-
- [% FOREACH user IN userlist %]
- [% NEXT IF user.isguest %]
- Name: [% user.name %] Email: [% user.email %]
- [% END %]
-
-The C<LAST> directive can be used to prematurely exit the loop. C<BREAK> is
-also provided as an alias for C<LAST>.
-
- [% FOREACH match IN results.nsort('score').reverse %]
- [% LAST IF match.score < 50 %]
- [% match.score %] : [% match.url %]
- [% END %]
-
-The C<FOREACH> directive is implemented using the L<Template::Iterator>
-module. A reference to the iterator object for a C<FOREACH> directive is
-implicitly available in the C<loop> variable. The following methods
-can be called on the C<loop> iterator.
-
- size() number of elements in the list
- max() index number of last element (size - 1)
- index() index of current iteration from 0 to max()
- count() iteration counter from 1 to size() (i.e. index() + 1)
- first() true if the current iteration is the first
- last() true if the current iteration is the last
- prev() return the previous item in the list
- next() return the next item in the list
-
-See L<Template::Iterator> for further details.
-
-Example:
-
- [% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%]
- [%- "<ul>\n" IF loop.first %]
- <li>[% loop.count %]/[% loop.size %]: [% item %]
- [%- "</ul>\n" IF loop.last %]
- [% END %]
-
-Output:
-
- <ul>
- <li>1/3: foo
- <li>2/3: bar
- <li>3/3: baz
- </ul>
-
-Nested loops will work as expected, with the C<loop> variable correctly
-referencing the innermost loop and being restored to any previous
-value (i.e. an outer loop) at the end of the loop.
-
- [% FOREACH group IN grouplist;
- # loop => group iterator
- "Groups:\n" IF loop.first;
-
- FOREACH user IN group.userlist;
- # loop => user iterator
- "$loop.count: $user.name\n";
- END;
-
- # loop => group iterator
- "End of Groups\n" IF loop.last;
- END
- %]
-
-The C<iterator> plugin can also be used to explicitly create an
-iterator object. This can be useful within nested loops where you
-need to keep a reference to the outer iterator within the inner loop.
-The iterator plugin effectively allows you to create an iterator by a
-name other than C<loop>. See L<Template::Plugin::Iterator> for further
-details.
-
- [% USE giter = iterator(grouplist) %]
-
- [% FOREACH group IN giter %]
- [% FOREACH user IN group.userlist %]
- user #[% loop.count %] in
- group [% giter.count %] is
- named [% user.name %]
- [% END %]
- [% END %]
-
-=head2 WHILE
-
-The C<WHILE> directive can be used to repeatedly process a template block
-while a conditional expression evaluates true. The expression may
-be arbitrarily complex as per C<IF> / C<UNLESS>.
-
- [% WHILE total < 100 %]
- ...
- [% total = calculate_new_total %]
- [% END %]
-
-An assignment can be enclosed in parenthesis to evaluate the assigned
-value.
-
- [% WHILE (user = get_next_user_record) %]
- [% user.name %]
- [% END %]
-
-The C<NEXT> directive can be used to start the next iteration of a
-C<WHILE> loop and C<BREAK> can be used to exit the loop, both as per C<FOREACH>.
-
-The Template Toolkit uses a failsafe counter to prevent runaway C<WHILE>
-loops which would otherwise never terminate. If the loop exceeds 1000
-iterations then an C<undef> exception will be thrown, reporting the
-error:
-
- WHILE loop terminated (> 1000 iterations)
-
-The C<$Template::Directive::WHILE_MAX> variable controls this behaviour
-and can be set to a higher value if necessary.
-
-=head1 Filters, Plugins, Macros and Perl
-
-=head2 FILTER
-
-The C<FILTER> directive can be used to post-process the output of a
-block. A number of standard filters are provided with the Template
-Toolkit. The C<html> filter, for example, escapes the 'E<lt>', 'E<gt>'
-and '&' characters to prevent them from being interpreted as HTML tags
-or entity reference markers.
-
- [% FILTER html %]
- HTML text may have < and > characters embedded
- which you want converted to the correct HTML entities.
- [% END %]
-
-output:
-
- HTML text may have < and > characters embedded
- which you want converted to the correct HTML entities.
-
-The C<FILTER> directive can also follow various other non-block directives.
-For example:
-
- [% INCLUDE mytext FILTER html %]
-
-The C<|> character can also be used as an alias for C<FILTER>.
-
- [% INCLUDE mytext | html %]
-
-Multiple filters can be chained together and will be called in sequence.
-
- [% INCLUDE mytext FILTER html FILTER html_para %]
-
-or
-
- [% INCLUDE mytext | html | html_para %]
-
-Filters come in two flavours, known as 'static' or 'dynamic'. A
-static filter is a simple subroutine which accepts a text string as
-the only argument and returns the modified text. The C<html> filter is
-an example of a static filter, implemented as:
-
- sub html_filter {
- my $text = shift;
- for ($text) {
- s/&/&/g;
- s/</</g;
- s/>/>/g;
- }
- return $text;
- }
-
-Dynamic filters can accept arguments which are specified when the filter
-is called from a template. The C<repeat> filter is such an example,
-accepting a numerical argument which specifies the number of times
-that the input text should be repeated.
-
- [% FILTER repeat(3) %]blah [% END %]
-
-output:
-
- blah blah blah
-
-These are implemented as filter 'factories'. The factory subroutine
-is passed a reference to the current L<Template::Context> object along
-with any additional arguments specified. It should then return a
-subroutine reference (e.g. a closure) which implements the filter.
-The C<repeat> filter factory is implemented like this:
-
- sub repeat_filter_factory {
- my ($context, $iter) = @_;
- $iter = 1 unless defined $iter;
-
- return sub {
- my $text = shift;
- $text = '' unless defined $text;
- return join('\n', $text) x $iter;
- }
- }
-
-The C<FILTERS> option, described in L<Template::Manual::Config>, allows custom
-filters to be defined when a Template object is instantiated. The
-L<define_filter()|Template::Context#define_filter()> method allows further
-filters to be defined at any time.
-
-When using a filter, it is possible to assign an alias to it for
-further use. This is most useful for dynamic filters that you want
-to re-use with the same configuration.
-
- [% FILTER echo = repeat(2) %]
- Is there anybody out there?
- [% END %]
-
- [% FILTER echo %]
- Mother, should I build a wall?
- [% END %]
-
-Output:
-
- Is there anybody out there?
- Is there anybody out there?
-
- Mother, should I build a wall?
- Mother, should I build a wall?
-
-The C<FILTER> directive automatically quotes the name of the filter. As
-with C<INCLUDE> et al, you can use a variable to provide the name of the
-filter, prefixed by C<$>.
-
- [% myfilter = 'html' %]
- [% FILTER $myfilter %] # same as [% FILTER html %]
- ...
- [% END %]
-
-A template variable can also be used to define a static filter
-subroutine. However, the Template Toolkit will automatically call any
-subroutine bound to a variable and use the value returned. Thus, the
-above example could be implemented as:
-
- my $vars = {
- myfilter => sub { return 'html' },
- };
-
-template:
-
- [% FILTER $myfilter %] # same as [% FILTER html %]
- ...
- [% END %]
-
-To define a template variable that evaluates to a subroutine reference
-that can be used by the C<FILTER> directive, you should create a
-subroutine that, when called automatically by the Template Toolkit,
-returns another subroutine reference which can then be used to perform
-the filter operation. Note that only static filters can be
-implemented in this way.
-
- my $vars = {
- myfilter => sub { \&my_filter_sub },
- };
-
- sub my_filter_sub {
- my $text = shift;
- # do something
- return $text;
- }
-
-template:
-
- [% FILTER $myfilter %]
- ...
- [% END %]
-
-Alternately, you can bless a subroutine reference into a class (any
-class will do) to fool the Template Toolkit into thinking it's an
-object rather than a subroutine. This will then bypass the automatic
-"call-a-subroutine-to-return-a-value" magic.
-
- my $vars = {
- myfilter => bless(\&my_filter_sub, 'anything_you_like'),
- };
-
-template:
-
- [% FILTER $myfilter %]
- ...
- [% END %]
-
-Filters bound to template variables remain local to the variable context in
-which they are defined. That is, if you define a filter in a C<PERL> block
-within a template that is loaded via C<INCLUDE>, then the filter definition
-will only exist until the end of that template when the stash is delocalised,
-restoring the previous variable state. If you want to define a filter which
-persists for the lifetime of the processor, or define additional dynamic
-filter factories, then you can call the
-L<define_filter()|Template::Context#define_filter()> method on the current
-L<Template::Context> object.
-
-See L<Template::Manual::Filters> for a complete list of available filters,
-their descriptions and examples of use.
-
-=head2 USE
-
-The C<USE> directive can be used to load and initialise "plugin"
-extension modules.
-
- [% USE myplugin %]
-
-A plugin is a regular Perl module that conforms to a particular
-object-oriented interface, allowing it to be loaded into and used
-automatically by the Template Toolkit. For details of this interface
-and information on writing plugins, consult L<Template::Plugin>.
-
-A number of standard plugins are included with the Template Toolkit
-(see below and L<Template::Manual::Plugins>). The names of these
-standard plugins are case insensitive.
-
- [% USE CGI %] # => Template::Plugin::CGI
- [% USE Cgi %] # => Template::Plugin::CGI
- [% USE cgi %] # => Template::Plugin::CGI
-
-You can also define further plugins using the C<PLUGINS> option.
-
- my $tt = Template->new({
- PLUGINS => {
- foo => 'My::Plugin::Foo',
- bar => 'My::Plugin::Bar',
- },
- });
-
-The recommended convention is to specify these plugin names in lower
-case. The Template Toolkit first looks for an exact case-sensitive
-match and then tries the lower case conversion of the name specified.
-
- [% USE Foo %] # look for 'Foo' then 'foo'
-
-If you define all your C<PLUGINS> with lower case names then they will be
-located regardless of how the user specifies the name in the C<USE>
-directive. If, on the other hand, you define your C<PLUGINS> with upper
-or mixed case names then the name specified in the C<USE> directive must
-match the case exactly.
-
-If the plugin isn't defined in either the standard plugins
-(C<$Template::Plugins::STD_PLUGINS>) or via the C<PLUGINS> option, then
-the C<PLUGIN_BASE> is searched.
-
-In this case the plugin name I<is> case-sensitive. It is appended to
-each of the C<PLUGIN_BASE> module namespaces in turn (default:
-C<Template::Plugin>) to construct a full module name which it attempts
-to locate and load. Any periods, 'C<.>', in the name will be converted
-to 'C<::>'.
-
- [% USE MyPlugin %] # => Template::Plugin::MyPlugin
- [% USE Foo.Bar %] # => Template::Plugin::Foo::Bar
-
-The C<LOAD_PERL> option (disabled by default) provides a further way by
-which external Perl modules may be loaded. If a regular Perl module
-(i.e. not a C<Template::Plugin::*> or other module relative to some
-C<PLUGIN_BASE>) supports an object-oriented interface and a C<new()>
-constructor then it can be loaded and instantiated automatically. The
-following trivial example shows how the IO::File module might be used.
-
- [% USE file = IO.File('/tmp/mydata') %]
-
- [% WHILE (line = file.getline) %]
- <!-- [% line %] -->
- [% END %]
-
-Any additional parameters supplied in parenthesis after the plugin
-name will be also be passed to the C<new()> constructor. A reference to
-the current L<Template::Context> object is passed as the first
-parameter.
-
- [% USE MyPlugin('foo', 123) %]
-
-equivalent to:
-
- Template::Plugin::MyPlugin->new($context, 'foo', 123);
-
-The only exception to this is when a module is loaded via the
-C<LOAD_PERL> option. In this case the C<$context> reference is I<not>
-passed to the C<new()> constructor. This is based on the assumption that
-the module is a regular Perl module rather than a Template Toolkit
-plugin so isn't expecting a context reference and wouldn't know what
-to do with it anyway.
-
-Named parameters may also be specified. These are collated into a
-hash which is passed by reference as the last parameter to the
-constructor, as per the general code calling interface.
-
- [% USE url('/cgi-bin/foo', mode='submit', debug=1) %]
-
-equivalent to:
-
- Template::Plugin::URL->new(
- $context,
- '/cgi-bin/foo'
- { mode => 'submit', debug => 1 }
- );
-
-The plugin may represent any data type; a simple variable, hash, list or
-code reference, but in the general case it will be an object reference.
-Methods can be called on the object (or the relevant members of the
-specific data type) in the usual way:
-
- [% USE table(mydata, rows=3) %]
-
- [% FOREACH row IN table.rows %]
- <tr>
- [% FOREACH item IN row %]
- <td>[% item %]</td>
- [% END %]
- </tr>
- [% END %]
-
-An alternative name may be provided for the plugin by which it can be
-referenced:
-
- [% USE scores = table(myscores, cols=5) %]
-
- [% FOREACH row IN scores.rows %]
- ...
- [% END %]
-
-You can use this approach to create multiple plugin objects with
-different configurations. This example shows how the
-L<format|Template::Plugin::Format> plugin is used to create
-sub-routines bound to variables for formatting text as per C<printf()>.
-
- [% USE bold = format('<b>%s</b>') %]
- [% USE ital = format('<i>%s</i>') %]
- [% bold('This is bold') %]
- [% ital('This is italic') %]
-
-Output:
-
- <b>This is bold</b>
- <i>This is italic</i>
-
-This next example shows how the L<URL|Template::Plugin::URL> plugin can be
-used to build dynamic URLs from a base part and optional query parameters.
-
- [% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %]
- <a href="[% mycgi %]">...
- <a href="[% mycgi(mode='submit') %]"...
-
-Output:
-
- <a href="/cgi-bin/foo.pl?debug=1">...
- <a href="/cgi-bin/foo.pl?mode=submit&debug=1">...
-
-The L<CGI|Template::Plugin::CGI> plugin is an example of one which delegates
-to another Perl module. In this case, to Lincoln Stein's C<CGI> module.
-All of the methods provided by the C<CGI> module are available via the plugin.
-
- [% USE CGI;
- CGI.start_form;
- CGI.checkbox_group( name = 'colours',
- values = [ 'red' 'green' 'blue' ] );
- CGI.popup_menu( name = 'items',
- values = [ 'foo' 'bar' 'baz' ] );
- CGI.end_form
- %]
-
-See L<Template::Manual::Plugins> for more information on the plugins
-distributed with the toolkit or available from CPAN.
-
-=head2 MACRO
-
-The C<MACRO> directive allows you to define a directive or directive block
-which is then evaluated each time the macro is called.
-
- [% MACRO header INCLUDE header %]
-
-Calling the macro as:
-
- [% header %]
-
-is then equivalent to:
-
- [% INCLUDE header %]
-
-Macros can be passed named parameters when called. These values remain
-local to the macro.
-
- [% header(title='Hello World') %]
-
-equivalent to:
-
- [% INCLUDE header title='Hello World' %]
-
-A C<MACRO> definition may include parameter names. Values passed to the
-macros are then mapped to these local variables. Other named parameters
-may follow these.
-
- [% MACRO header(title) INCLUDE header %]
- [% header('Hello World') %]
- [% header('Hello World', bgcol='#123456') %]
-
-equivalent to:
-
- [% INCLUDE header title='Hello World' %]
- [% INCLUDE header title='Hello World' bgcol='#123456' %]
-
-Here's another example, defining a macro for display numbers
-in comma-delimited groups of 3, using the chunk and join virtual
-method.
-
- [% MACRO number(n) GET n.chunk(-3).join(',') %]
- [% number(1234567) %] # 1,234,567
-
-A C<MACRO> may precede any directive and must conform to the structure
-of the directive.
-
- [% MACRO header IF frames %]
- [% INCLUDE frames/header %]
- [% ELSE %]
- [% INCLUDE header %]
- [% END %]
-
- [% header %]
-
-A C<MACRO> may also be defined as an anonymous C<BLOCK>. The block will be
-evaluated each time the macro is called.
-
- [% MACRO header BLOCK %]
- ...content...
- [% END %]
-
- [% header %]
-
-If you've got the C<EVAL_PERL> option set, then you can even define a
-C<MACRO> as a C<PERL> block (see below):
-
- [% MACRO triple(n) PERL %]
- my $n = $stash->get('n');
- print $n * 3;
- [% END -%]
-
-=head2 PERL
-
-(for the advanced reader)
-
-The C<PERL> directive is used to mark the start of a block which contains
-Perl code for evaluation. The C<EVAL_PERL> option must be enabled for Perl
-code to be evaluated or a C<perl> exception will be thrown with the
-message 'C<EVAL_PERL not set>'.
-
-Perl code is evaluated in the C<Template::Perl> package. The C<$context>
-package variable contains a reference to the current L<Template::Context>
-object. This can be used to access the functionality of the Template
-Toolkit to process other templates, load plugins, filters, etc.
-See L<Template::Context> for further details.
-
- [% PERL %]
- print $context->include('myfile');
- [% END %]
-
-The L<$stash> variable contains a reference to the top-level stash object
-which manages template variables. Through this, variable values can
-be retrieved and updated. See L<Template::Stash> for further details.
-
- [% PERL %]
- $stash->set(foo => 'bar');
- print "foo value: ", $stash->get('foo');
- [% END %]
-
-Output:
-
- foo value: bar
-
-Output is generated from the C<PERL> block by calling C<print()>. Note that
-the C<Template::Perl::PERLOUT> handle is selected (tied to an output
-buffer) instead of C<STDOUT>.
-
- [% PERL %]
- print "foo\n"; # OK
- print PERLOUT "bar\n"; # OK, same as above
- print Template::Perl::PERLOUT "baz\n"; # OK, same as above
- print STDOUT "qux\n"; # WRONG!
- [% END %]
-
-The C<PERL> block may contain other template directives. These are
-processed before the Perl code is evaluated.
-
- [% name = 'Fred Smith' %]
-
- [% PERL %]
- print "[% name %]\n";
- [% END %]
-
-Thus, the Perl code in the above example is evaluated as:
-
- print "Fred Smith\n";
-
-Exceptions may be thrown from within C<PERL> blocks using C<die()>.
-They will be correctly caught by enclosing C<TRY> blocks.
-
- [% TRY %]
- [% PERL %]
- die "nothing to live for\n";
- [% END %]
- [% CATCH %]
- error: [% error.info %]
- [% END %]
-
-output:
- error: nothing to live for
-
-=head2 RAWPERL
-
-(for the very advanced reader)
-
-The Template Toolkit parser reads a source template and generates the
-text of a Perl subroutine as output. It then uses C<eval()> to evaluate
-it into a subroutine reference. This subroutine is then called to
-process the template, passing a reference to the current
-L<Template::Context> object through which the functionality of the
-Template Toolkit can be accessed. The subroutine reference can be
-cached, allowing the template to be processed repeatedly without
-requiring any further parsing.
-
-For example, a template such as:
-
- [% PROCESS header %]
- The [% animal %] sat on the [% location %]
- [% PROCESS footer %]
-
-is converted into the following Perl subroutine definition:
-
- sub {
- my $context = shift;
- my $stash = $context->stash;
- my $output = '';
- my $error;
-
- eval { BLOCK: {
- $output .= $context->process('header');
- $output .= "The ";
- $output .= $stash->get('animal');
- $output .= " sat on the ";
- $output .= $stash->get('location');
- $output .= $context->process('footer');
- $output .= "\n";
- } };
- if ($@) {
- $error = $context->catch($@, \$output);
- die $error unless $error->type eq 'return';
- }
-
- return $output;
- }
-
-To examine the Perl code generated, such as in the above example, set
-the C<$Template::Parser::DEBUG> package variable to any true value. You
-can also set the C<$Template::Directive::PRETTY> variable true to have
-the code formatted in a readable manner for human consumption. The
-source code for each generated template subroutine will be printed to
-C<STDERR> on compilation (i.e. the first time a template is used).
-
- $Template::Parser::DEBUG = 1;
- $Template::Directive::PRETTY = 1;
-
- $template->process($file, $vars)
- || die $template->error(), "\n";
-
-The C<PERL> ... C<END> construct allows Perl code to be embedded into a
-template when the C<EVAL_PERL> option is set. It is evaluated at
-"runtime" using C<eval()> each time the template subroutine is called.
-This is inherently flexible, but not as efficient as it could be,
-especially in a persistent server environment where a template may be
-processed many times.
-
-The C<RAWPERL> directive allows you to write Perl code that is integrated
-directly into the generated Perl subroutine text. It is evaluated
-once at compile time and is stored in cached form as part of the
-compiled template subroutine. This makes C<RAWPERL> blocks more
-efficient than C<PERL> blocks.
-
-The downside is that you must code much closer to the metal. For example, in a
-C<PERL> block you can call L<print()> to generate some output. C<RAWPERL>
-blocks don't afford such luxury. The code is inserted directly into the
-generated subroutine text and should conform to the convention of appending to
-the C<$output> variable.
-
- [% PROCESS header %]
-
- [% RAWPERL %]
- $output .= "Some output\n";
- ...
- $output .= "Some more output\n";
- [% END %]
-
-The critical section of the generated subroutine for this example would
-then look something like:
-
- ...
- eval { BLOCK: {
- $output .= $context->process('header');
- $output .= "\n";
- $output .= "Some output\n";
- ...
- $output .= "Some more output\n";
- $output .= "\n";
- } };
- ...
-
-As with C<PERL> blocks, the L<$context|Template::Context> and
-L<$stash|Template::Stash> references are pre-defined and available for use
-within C<RAWPERL> code.
-
-=head1 Exception Handling and Flow Control
-
-=head2 TRY / THROW / CATCH / FINAL
-
-(more advanced material)
-
-The Template Toolkit supports fully functional, nested exception
-handling. The C<TRY> directive introduces an exception handling scope
-which continues until the matching C<END> directive. Any errors that
-occur within that block will be caught and can be handled by one
-of the C<CATCH> blocks defined.
-
- [% TRY %]
- ...blah...blah...
- [% CALL somecode %]
- ...etc...
- [% INCLUDE someblock %]
- ...and so on...
- [% CATCH %]
- An error occurred!
- [% END %]
-
-Errors are raised as exceptions (objects of the L<Template::Exception> class)
-which contain two fields: C<type> and C<info>. The exception C<type> is used
-to indicate the kind of error that occurred. It is a simple text string which
-can contain letters, numbers, 'C<_>' or 'C<.>'. The C<info> field contains an
-error message indicating what actually went wrong. Within a catch block, the
-exception object is aliased to the C<error> variable. You can access the C<type>
-and C<info> fields directly.
-
- [% mydsn = 'dbi:MySQL:foobar' %]
- ...
-
- [% TRY %]
- [% USE DBI(mydsn) %]
- [% CATCH %]
- ERROR! Type: [% error.type %]
- Info: [% error.info %]
- [% END %]
-
-output (assuming a non-existent database called 'C<foobar>'):
-
- ERROR! Type: DBI
- Info: Unknown database "foobar"
-
-The C<error> variable can also be specified by itself and will return a
-string of the form "C<$type error - $info>".
-
- ...
- [% CATCH %]
- ERROR: [% error %]
- [% END %]
-
-Output:
-
- ERROR: DBI error - Unknown database "foobar"
-
-Each C<CATCH> block may be specified with a particular exception type
-denoting the kind of error that it should catch. Multiple C<CATCH>
-blocks can be provided to handle different types of exception that may
-be thrown in the C<TRY> block. A C<CATCH> block specified without any type,
-as in the previous example, is a default handler which will catch any
-otherwise uncaught exceptions. This can also be specified as
-C<[% CATCH DEFAULT %]>.
-
- [% TRY %]
- [% INCLUDE myfile %]
- [% USE DBI(mydsn) %]
- [% CALL somecode %]
- [% CATCH file %]
- File Error! [% error.info %]
- [% CATCH DBI %]
- [% INCLUDE database/error.html %]
- [% CATCH %]
- [% error %]
- [% END %]
-
-Remember that you can specify multiple directives within a single tag,
-each delimited by 'C<;>'. So the above example can be written more
-concisely as:
-
- [% TRY;
- INCLUDE myfile;
- USE DBI(mydsn);
- CALL somecode;
- CATCH file;
- "File Error! $error.info";
- CATCH DBI;
- INCLUDE database/error.html;
- CATCH;
- error;
- END
- %]
-
-The C<DBI> plugin throws exceptions of the C<DBI> type (in case that
-wasn't already obvious). The other specific exception caught here is
-of the C<file> type.
-
-A C<file> exception is automatically thrown by the Template Toolkit when it
-can't find a file, or fails to load, parse or process a file that has been
-requested by an C<INCLUDE>, C<PROCESS>, C<INSERT> or C<WRAPPER> directive.
-If C<myfile> can't be found in the example above, the C<[% INCLUDE myfile %]>
-directive will raise a C<file> exception which is then caught by the
-C<[% CATCH file %]> block. The output generated would be:
-
- File Error! myfile: not found
-
-Note that the C<DEFAULT> option (disabled by default) allows you to specify a
-default file to be used any time a template file can't be found. This will
-prevent file exceptions from ever being raised when a non-existent file is
-requested (unless, of course, the C<DEFAULT> file your specify doesn't exist).
-Errors encountered once the file has been found (i.e. read error, parse error)
-will be raised as file exceptions as per usual.
-
-Uncaught exceptions (i.e. if the C<TRY> block doesn't have a type specific or
-default C<CATCH> handler) may be caught by enclosing C<TRY> blocks which can
-be nested indefinitely across multiple templates. If the error isn't caught at
-any level then processing will stop and the Template
-L<process()|Template#process()> method will return a false value to the
-caller. The relevant L<Template::Exception> object can be retrieved by calling
-the L<error()|Template#error()> method.
-
- [% TRY %]
- ...
- [% TRY %]
- [% INCLUDE $user.header %]
- [% CATCH file %]
- [% INCLUDE header %]
- [% END %]
- ...
- [% CATCH DBI %]
- [% INCLUDE database/error.html %]
- [% END %]
-
-In this example, the inner C<TRY> block is used to ensure that the first
-C<INCLUDE> directive works as expected. We're using a variable to
-provide the name of the template we want to include, C<user.header>, and
-it's possible this contains the name of a non-existent template, or
-perhaps one containing invalid template directives. If the C<INCLUDE> fails
-with a C<file> error then we C<CATCH> it in the inner block and C<INCLUDE>
-the default C<header> file instead. Any C<DBI> errors that occur within
-the scope of the outer C<TRY> block will be caught in the relevant C<CATCH>
-block, causing the C<database/error.html> template to be processed.
-Note that included templates inherit all currently defined template
-variable so these error files can quite happily access the <error>
-variable to retrieve information about the currently caught exception.
-For example, the C<database/error.html> template might look like this:
-
- <h2>Database Error</h2>
- A database error has occurred: [% error.info %]
-
-You can also specify a C<FINAL> block. This is always processed
-regardless of the outcome of the C<TRY> and/or C<CATCH> blocks. If an
-exception is uncaught then the C<FINAL> block is processed before jumping
-to the enclosing block or returning to the caller.
-
- [% TRY %]
- ...
- [% CATCH this %]
- ...
- [% CATCH that %]
- ...
- [% FINAL %]
- All done!
- [% END %]
-
-The output from the C<TRY> block is left intact up to the point where an
-exception occurs. For example, this template:
-
- [% TRY %]
- This gets printed
- [% THROW food 'carrots' %]
- This doesn't
- [% CATCH food %]
- culinary delights: [% error.info %]
- [% END %]
-
-generates the following output:
-
- This gets printed
- culinary delights: carrots
-
-The C<CLEAR> directive can be used in a C<CATCH> or C<FINAL> block to clear
-any output created in the C<TRY> block.
-
- [% TRY %]
- This gets printed
- [% THROW food 'carrots' %]
- This doesn't
- [% CATCH food %]
- [% CLEAR %]
- culinary delights: [% error.info %]
- [% END %]
-
-Output:
-
- culinary delights: carrots
-
-Exception types are hierarchical, with each level being separated by
-the familiar dot operator. A C<DBI.connect> exception is a more
-specific kind of C<DBI> error. Similarly, an C<example.error.barf> is a
-more specific kind of C<example.error> type which itself is also a
-C<example> error.
-
-A C<CATCH> handler that specifies a general exception
-type (such as C<DBI> or C<example.error>) will also catch more specific
-types that have the same prefix as long as a more specific handler
-isn't defined. Note that the order in which C<CATCH> handlers are
-defined is irrelevant; a more specific handler will always catch an
-exception in preference to a more generic or default one.
-
- [% TRY %]
- ...
- [% CATCH DBI ;
- INCLUDE database/error.html ;
- CATCH DBI.connect ;
- INCLUDE database/connect.html ;
- CATCH ;
- INCLUDE error.html ;
- END
- %]
-
-In this example, a C<DBI.connect> error has it's own handler, a more general
-C<DBI> block is used for all other C<DBI> or C<DBI.*> errors and a default
-handler catches everything else.
-
-Exceptions can be raised in a template using the C<THROW> directive. The
-first parameter is the exception type which doesn't need to be quoted
-(but can be, it's the same as C<INCLUDE>) followed by the relevant error
-message which can be any regular value such as a quoted string,
-variable, etc.
-
- [% THROW food "Missing ingredients: $recipe.error" %]
- [% THROW user.login 'no user id: please login' %]
- [% THROW $myerror.type "My Error: $myerror.info" %]
-
-It's also possible to specify additional positional or named
-parameters to the C<THROW> directive if you want to pass more than
-just a simple message back as the error info field.
-
- [% THROW food 'eggs' 'flour' msg='Missing Ingredients' %]
-
-In this case, the error C<info> field will be a hash array containing the
-named arguments and an C<args> item which contains a list of the positional
-arguments.
-
- type => 'food',
- info => {
- msg => 'Missing Ingredients',
- args => ['eggs', 'flour'],
- }
-
-In addition to specifying individual positional arguments as
-C<[% error.info.args.n %]>, the C<info> hash contains keys directly
-pointing to the positional arguments, as a convenient shortcut.
-
- [% error.info.0 %] # same as [% error.info.args.0 %]
-
-Exceptions can also be thrown from Perl code which you've bound to
-template variables, or defined as a plugin or other extension. To
-raise an exception, call C<die()> passing a reference to a
-L<Template::Exception> object as the argument. This will then be caught
-by any enclosing C<TRY> blocks from where the code was called.
-
- use Template::Exception;
- ...
- my $vars = {
- foo => sub {
- # ... do something ...
- die Template::Exception->new('myerr.naughty',
- 'Bad, bad error');
- },
- };
-
-Template:
-
- [% TRY %]
- [% foo %]
- [% CATCH myerr ;
- "Error: $error" ;
- END
- %]
-
-Output:
-
- Error: myerr.naughty error - Bad, bad error
-
-The C<info> field can also be a reference to another object or data
-structure, if required.
-
- die Template::Exception->new('myerror', {
- module => 'foo.pl',
- errors => [ 'bad permissions', 'naughty boy' ],
- });
-
-Later, in a template:
-
- [% TRY %]
- ...
- [% CATCH myerror %]
- [% error.info.errors.size or 'no';
- error.info.errors.size == 1 ? ' error' : ' errors' %]
- in [% error.info.module %]:
- [% error.info.errors.join(', ') %].
- [% END %]
-
-Generating the output:
-
- 2 errors in foo.pl:
- bad permissions, naughty boy.
-
-You can also call C<die()> with a single string, as is common in much
-existing Perl code. This will automatically be converted to an
-exception of the 'C<undef>' type (that's the literal string 'C<undef>',
-not the undefined value). If the string isn't terminated with a
-newline then Perl will append the familiar C<" at $file line $line">
-message.
-
- sub foo {
- # ... do something ...
- die "I'm sorry, Dave, I can't do that\n";
- }
-
-If you're writing a plugin, or some extension code that has the current
-L<Template::Context> in scope (you can safely skip this section if this means
-nothing to you) then you can also raise an exception by calling the context
-L<throw()|Template::Context#throw()> method. You can pass it an
-L<Template::Exception> object reference, a pair of C<($type, $info)>
-parameters or just an C<$info> string to create an exception of 'C<undef>' type.
-
- $context->throw($e); # exception object
- $context->throw('Denied'); # 'undef' type
- $context->throw('user.passwd', 'Bad Password');
-
-=head2 NEXT
-
-The C<NEXT> directive can be used to start the next iteration of a C<FOREACH>
-or C<WHILE> loop.
-
- [% FOREACH user IN users %]
- [% NEXT IF user.isguest %]
- Name: [% user.name %] Email: [% user.email %]
- [% END %]
-
-=head2 LAST
-
-The C<LAST> directive can be used to prematurely exit a C<FOREACH> or C<WHILE>
-loop.
-
- [% FOREACH user IN users %]
- Name: [% user.name %] Email: [% user.email %]
- [% LAST IF some.condition %]
- [% END %]
-
-C<BREAK> can also be used as an alias for C<LAST>.
-
-=head2 RETURN
-
-The C<RETURN> directive can be used to stop processing the current template
-and return to the template from which it was called, resuming processing at
-the point immediately after the C<INCLUDE>, C<PROCESS> or C<WRAPPER>
-directive. If there is no enclosing template then the Template
-L<process()|Template#process()> method will return to the calling code with a
-true value.
-
- Before
- [% INCLUDE half_wit %]
- After
-
- [% BLOCK half_wit %]
- This is just half...
- [% RETURN %]
- ...a complete block
- [% END %]
-
-Output:
-
- Before
- This is just half...
- After
-
-=head2 STOP
-
-The C<STOP> directive can be used to indicate that the processor should stop
-gracefully without processing any more of the template document. This is a
-planned stop and the Template L<process()|Template#process()> method will
-return a B<true> value to the caller. This indicates that the template was
-processed successfully according to the directives within it.
-
- [% IF something.terrible.happened %]
- [% INCLUDE fatal/error.html %]
- [% STOP %]
- [% END %]
-
- [% TRY %]
- [% USE DBI(mydsn) %]
- ...
- [% CATCH DBI.connect %]
- <h1>Cannot connect to the database: [% error.info %]</h1>
- <p>
- We apologise for the inconvenience.
- </p>
- [% INCLUDE footer %]
- [% STOP %]
- [% END %]
-
-=head2 CLEAR
-
-The C<CLEAR> directive can be used to clear the output buffer for the current
-enclosing block. It is most commonly used to clear the output generated
-from a C<TRY> block up to the point where the error occurred.
-
- [% TRY %]
- blah blah blah # this is normally left intact
- [% THROW some 'error' %] # up to the point of error
- ...
- [% CATCH %]
- [% CLEAR %] # clear the TRY output
- [% error %] # print error string
- [% END %]
-
-=head1 Miscellaneous
-
-=head2 META
-
-The C<META> directive allows simple metadata items to be defined within a
-template. These are evaluated when the template is parsed and as such may only
-contain simple values (e.g. it's not possible to interpolate other variables
-values into C<META> variables).
-
- [% META
- title = 'The Cat in the Hat'
- author = 'Dr. Seuss'
- version = 1.23
- %]
-
-The C<template> variable contains a reference to the main template
-being processed. These metadata items may be retrieved as attributes
-of the template.
-
- <h1>[% template.title %]</h1>
- <h2>[% template.author %]</h2>
-
-The C<name> and C<modtime> metadata items are automatically defined for each
-template to contain its name and modification time in seconds since the epoch.
-
- [% USE date %] # use Date plugin to format time
- ...
- [% template.name %] last modified
- at [% date.format(template.modtime) %]
-
-The C<PRE_PROCESS> and C<POST_PROCESS> options allow common headers and
-footers to be added to all templates. The C<template> reference is
-correctly defined when these templates are processed, allowing headers
-and footers to reference metadata items from the main template.
-
- $template = Template->new({
- PRE_PROCESS => 'header',
- POST_PROCESS => 'footer',
- });
-
- $template->process('cat_in_hat');
-
-header:
-
- <html>
- <head>
- <title>[% template.title %]</title>
- </head>
- <body>
-
-cat_in_hat:
-
- [% META
- title = 'The Cat in the Hat'
- author = 'Dr. Seuss'
- version = 1.23
- year = 2000
- %]
-
- The cat in the hat sat on the mat.
-
-footer:
-
- <hr>
- © [% template.year %] [% template.author %]
- </body>
- </html>
-
-The output generated from the above example is:
-
- <html>
- <head>
- <title>The Cat in the Hat</title>
- </head>
- <body>
- The cat in the hat sat on the mat.
- <hr>
- © 2000 Dr. Seuss
- </body>
- </html>
-
-=head2 TAGS
-
-The C<TAGS> directive can be used to set the C<START_TAG> and C<END_TAG> values
-on a per-template file basis.
-
- [% TAGS <+ +> %]
-
- <+ INCLUDE header +>
-
-The TAGS directive may also be used to set a named C<TAG_STYLE>
-
- [% TAGS html %]
- <!-- INCLUDE header -->
-
-See the L<TAGS|Template::Manual::Config#TAGS> and L<TAG_STYLE|Template::Manual::Config#TAG_STYLE>
-configuration options for further details.
-
-=head2 DEBUG
-
-The C<DEBUG> directive can be used to enable or disable directive debug
-messages within a template. The C<DEBUG> configuration option must be
-set to include C<DEBUG_DIRS> for the C<DEBUG> directives to have any effect.
-If C<DEBUG_DIRS> is not set then the parser will automatically ignore and
-remove any C<DEBUG> directives.
-
-The C<DEBUG> directive can be used with an C<on> or C<off> parameter to
-enable or disable directive debugging messages from that point
-forward. When enabled, the output of each directive in the generated
-output will be prefixed by a comment indicate the file, line and
-original directive text.
-
- [% DEBUG on %]
- directive debugging is on (assuming DEBUG option is set true)
- [% DEBUG off %]
- directive debugging is off
-
-The C<format> parameter can be used to change the format of the debugging
-message.
-
- [% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Filters
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=encoding latin1
-
-=head1 NAME
-
-Template::Manual::Filters - Standard filters
-
-=head1 format(format)
-
-The C<format> filter takes a format string as a parameter (as per
-C<printf()>) and formats each line of text accordingly.
-
- [% FILTER format('<!-- %-40s -->') %]
- This is a block of text filtered
- through the above format.
- [% END %]
-
-Output:
-
- <!-- This is a block of text filtered -->
- <!-- through the above format. -->
-
-=head1 upper
-
-Folds the input to UPPER CASE.
-
- [% "hello world" FILTER upper %]
-
-Output:
-
- HELLO WORLD
-
-=head1 lower
-
-Folds the input to lower case.
-
- [% "Hello World" FILTER lower %]
-
-Output:
-
- hello world
-
-=head1 ucfirst
-
-Folds the first character of the input to UPPER CASE.
-
- [% "hello" FILTER ucfirst %]
-
-Output:
-
- Hello
-
-=head1 lcfirst
-
-Folds the first character of the input to lower case.
-
- [% "HELLO" FILTER lcfirst %]
-
-Output:
-
- hELLO
-
-=head1 trim
-
-Trims any leading or trailing whitespace from the input text. Particularly
-useful in conjunction with C<INCLUDE>, C<PROCESS>, etc., having the same effect
-as the C<TRIM> configuration option.
-
- [% INCLUDE myfile | trim %]
-
-=head1 collapse
-
-Collapse any whitespace sequences in the input text into a single space.
-Leading and trailing whitespace (which would be reduced to a single space)
-is removed, as per trim.
-
- [% FILTER collapse %]
-
- The cat
-
- sat on
-
- the mat
-
- [% END %]
-
-Output:
-
- The cat sat on the mat
-
-=head1 html
-
-Converts the characters C<E<lt>>, C<E<gt>>, C<&> and C<"> to C<<>,
-C<>>, C<&>, and C<"> respectively, protecting them from being
-interpreted as representing HTML tags or entities.
-
- [% FILTER html %]
- Binary "<=>" returns -1, 0, or 1 depending on...
- [% END %]
-
-Output:
-
- Binary "<=>" returns -1, 0, or 1 depending on...
-
-=head1 html_entity
-
-The C<html> filter is fast and simple but it doesn't encode the full
-range of HTML entities that your text may contain. The C<html_entity>
-filter uses either the C<Apache::Util> module (which is written in C and
-is therefore faster) or the C<HTML::Entities> module (written in Perl but
-equally as comprehensive) to perform the encoding.
-
-If one or other of these modules are installed on your system then the text
-will be encoded (via the C<escape_html()> or C<encode_entities()> subroutines
-respectively) to convert all extended characters into their appropriate HTML
-entities (e.g. converting 'C<?>' to 'C<é>'). If neither module is
-available on your system then an 'C<html_entity>' exception will be thrown
-reporting an appropriate message.
-
-If you want to force TT to use one of the above modules in preference to
-the other, then call either of the L<Template::Filters> class methods:
-L<use_html_entities()|Template::Filters/use_html_entities()> or
-L<use_apache_util()|Template::Filters/use_apache_util()>.
-
- use Template::Filters;
- Template::Filters->use_html_entities;
-
-For further information on HTML entity encoding, see
-L<http://www.w3.org/TR/REC-html40/sgml/entities.html>.
-
-=head1 xml
-
-Same as the C<html> filter, but adds C<'> which is the fifth XML
-built-in entity.
-
-=head1 html_para
-
-This filter formats a block of text into HTML paragraphs. A sequence of
-two or more newlines is used as the delimiter for paragraphs which are
-then wrapped in HTML C<E<lt>pE<gt>>...C<E<lt>/pE<gt>> tags.
-
- [% FILTER html_para %]
- The cat sat on the mat.
-
- Mary had a little lamb.
- [% END %]
-
-Output:
-
- <p>
- The cat sat on the mat.
- </p>
-
- <p>
- Mary had a little lamb.
- </p>
-
-=head1 html_break / html_para_break
-
-Similar to the html_para filter described above, but uses the HTML tag
-sequence C<E<lt>brE<gt>E<lt>brE<gt>> to join paragraphs.
-
- [% FILTER html_break %]
- The cat sat on the mat.
-
- Mary had a little lamb.
- [% END %]
-
-Output:
-
- The cat sat on the mat.
- <br>
- <br>
- Mary had a little lamb.
-
-=head1 html_line_break
-
-This filter replaces any newlines with C<E<lt>brE<gt>> HTML tags,
-thus preserving the line breaks of the original text in the
-HTML output.
-
- [% FILTER html_line_break %]
- The cat sat on the mat.
- Mary had a little lamb.
- [% END %]
-
-Output:
-
- The cat sat on the mat.<br>
- Mary had a little lamb.<br>
-
-=head1 uri
-
-This filter URI escapes the input text, converting any characters
-outside of the permitted URI character set (as defined by RFC 3986)
-into a C<%nn> hex escape.
-
- [% 'my file.html' | uri %]
-
-Output:
-
- my%20file.html
-
-The uri filter correctly encodes all reserved characters, including
-C<&>, C<@>, C</>, C<;>, C<:>, C<=>, C<+>, C<?> and C<$>. This filter
-is typically used to encode parameters in a URL that could otherwise
-be interpreted as part of the URL. Here's an example:
-
- [% path = 'http://tt2.org/example'
- back = '/other?foo=bar&baz=bam'
- title = 'Earth: "Mostly Harmless"'
- %]
- <a href="[% path %]?back=[% back | uri %]&title=[% title | uri %]">
-
-The output generated is rather long so we'll show it split across two
-lines:
-
- <a href="http://tt2.org/example?back=%2Fother%3Ffoo%3Dbar%26
- baz%3Dbam&title=Earth%3A%20%22Mostly%20Harmless%22">
-
-Without the uri filter the output would look like this (also split across
-two lines).
-
- <a href="http://tt2.org/example?back=/other?foo=bar
- &baz=bam&title=Earth: "Mostly Harmless"">
-
-In this rather contrived example we've manage to generate both a broken URL
-(the repeated C<?> is not allowed) and a broken HTML element (the href
-attribute is terminated by the first C<"> after C<Earth: > leaving C<Mostly
-Harmless"> dangling on the end of the tag in precisely the way that harmless
-things shouldn't dangle). So don't do that. Always use the uri filter to
-encode your URL parameters.
-
-However, you should B<not> use the uri filter to encode an entire URL.
-
- <a href="[% page_url | uri %]"> # WRONG!
-
-This will incorrectly encode any reserved characters like C<:> and C</>
-and that's almost certainly not what you want in this case. Instead
-you should use the B<url> (note spelling) filter for this purpose.
-
- <a href="[% page_url | url %]"> # CORRECT
-
-Please note that this behaviour was changed in version 2.16 of the
-Template Toolkit. Prior to that, the uri filter did not encode the
-reserved characters, making it technically incorrect according to the
-RFC 2396 specification (since superceded by RFC2732 and RFC3986). So we
-fixed it in 2.16 and provided the url filter to implement the old behaviour
-of not encoding reserved characters.
-
-As of version 2.26 of the Template Toolkit, the C<uri> and L<url> filters
-use the unsafe character set defined by RFC3986. This means that certain
-characters ("(", ")", "~", "*", "!" and the single quote "'") are now deemed
-unsafe and will be escaped as hex character sequences. The double quote
-character ('"') is now deemed safe and will not be escaped.
-
-If you want to enable the old behaviour then call the C<use_rfc2732()>
-method in L<Template::Filters>
-
- use Template::Filters
- Template::Filters->use_rfc2732;
-
-=head1 url
-
-The url filter is a less aggressive version of the uri filter. It encodes
-any characters outside of the permitted URI character set (as defined by RFC 2396)
-into C<%nn> hex escapes. However, unlike the uri filter, the url filter does
-B<not> encode the reserved characters C<&>, C<@>, C</>, C<;>, C<:>, C<=>, C<+>,
-C<?> and C<$>.
-
-=head1 indent(pad)
-
-Indents the text block by a fixed pad string or width. The 'C<pad>' argument
-can be specified as a string, or as a numerical value to indicate a pad
-width (spaces). Defaults to 4 spaces if unspecified.
-
- [% FILTER indent('ME> ') %]
- blah blah blah
- cabbages, rhubard, onions
- [% END %]
-
-Output:
-
- ME> blah blah blah
- ME> cabbages, rhubard, onions
-
-=head1 truncate(length,dots)
-
-Truncates the text block to the length specified, or a default length
-of 32. Truncated text will be terminated with 'C<...>' (i.e. the 'C<...>'
-falls inside the required length, rather than appending to it).
-
- [% FILTER truncate(21) %]
- I have much to say on this matter that has previously
- been said on more than one occasion.
- [% END %]
-
-Output:
-
- I have much to say...
-
-If you want to use something other than 'C<...>' you can pass that as a
-second argument.
-
- [% FILTER truncate(26, '…') %]
- I have much to say on this matter that has previously
- been said on more than one occasion.
- [% END %]
-
-Output:
-
- I have much to say…
-
-=head1 repeat(iterations)
-
-Repeats the text block for as many iterations as are specified (default: 1).
-
- [% FILTER repeat(3) %]
- We want more beer and we want more beer,
- [% END %]
- We are the more beer wanters!
-
-Output:
-
- We want more beer and we want more beer,
- We want more beer and we want more beer,
- We want more beer and we want more beer,
- We are the more beer wanters!
-
-=head1 remove(string)
-
-Searches the input text for any occurrences of the specified string and
-removes them. A Perl regular expression may be specified as the search
-string.
-
- [% "The cat sat on the mat" FILTER remove('\s+') %]
-
-Output:
-
- Thecatsatonthemat
-
-=head1 replace(search, replace)
-
-Similar to the remove filter described above, but taking a second parameter
-which is used as a replacement string for instances of the search string.
-
- [% "The cat sat on the mat" | replace('\s+', '_') %]
-
-Output:
-
- The_cat_sat_on_the_mat
-
-=head1 redirect(file, options)
-
-The C<redirect> filter redirects the output of the block into a separate
-file, specified relative to the C<OUTPUT_PATH> configuration item.
-
- [% FOREACH user IN myorg.userlist %]
- [% FILTER redirect("users/${user.id}.html") %]
- [% INCLUDE userinfo %]
- [% END %]
- [% END %]
-
-or more succinctly, using side-effect notation:
-
- [% FOREACH user IN myorg.userlist;
- INCLUDE userinfo
- FILTER redirect("users/${user.id}.html");
- END
- %]
-
-A C<file> exception will be thrown if the C<OUTPUT_PATH> option is undefined.
-
-An optional C<binmode> argument can follow the filename to explicitly set
-the output file to binary mode.
-
- [% PROCESS my/png/generator
- FILTER redirect("images/logo.png", binmode=1) %]
-
-For backwards compatibility with earlier versions, a single true/false
-value can be used to set binary mode.
-
- [% PROCESS my/png/generator
- FILTER redirect("images/logo.png", 1) %]
-
-For the sake of future compatibility and clarity, if nothing else, we
-would strongly recommend you explicitly use the named C<binmode> option
-as shown in the first example.
-
-=head1 eval / evaltt
-
-The C<eval> filter evaluates the block as template text, processing
-any directives embedded within it. This allows template variables to
-contain template fragments, or for some method to be provided for
-returning template fragments from an external source such as a
-database, which can then be processed in the template as required.
-
- my $vars = {
- fragment => "The cat sat on the [% place %]",
- };
- $template->process($file, $vars);
-
-The following example:
-
- [% fragment | eval %]
-
-is therefore equivalent to
-
- The cat sat on the [% place %]
-
-The C<evaltt> filter is provided as an alias for C<eval>.
-
-=head1 perl / evalperl
-
-The C<perl> filter evaluates the block as Perl code. The C<EVAL_PERL>
-option must be set to a true value or a C<perl> exception will be
-thrown.
-
- [% my_perl_code | perl %]
-
-In most cases, the C<[% PERL %]> ... C<[% END %]> block should suffice for
-evaluating Perl code, given that template directives are processed
-before being evaluate as Perl. Thus, the previous example could have
-been written in the more verbose form:
-
- [% PERL %]
- [% my_perl_code %]
- [% END %]
-
-as well as
-
- [% FILTER perl %]
- [% my_perl_code %]
- [% END %]
-
-The C<evalperl> filter is provided as an alias for C<perl> for backwards
-compatibility.
-
-=head1 stdout(options)
-
-The stdout filter prints the output generated by the enclosing block to
-C<STDOUT>. The C<binmode> option can be passed as either a named parameter
-or a single argument to set C<STDOUT> to binary mode (see the
-binmode perl function).
-
- [% PROCESS something/cool
- FILTER stdout(binmode=1) # recommended %]
-
- [% PROCESS something/cool
- FILTER stdout(1) # alternate %]
-
-The C<stdout> filter can be used to force C<binmode> on C<STDOUT>, or also
-inside C<redirect>, C<null> or C<stderr> blocks to make sure that particular
-output goes to C<STDOUT>. See the C<null> filter below for an example.
-
-=head1 stderr
-
-The stderr filter prints the output generated by the enclosing block to
-C<STDERR>.
-
-=head1 null
-
-The C<null> filter prints nothing. This is useful for plugins whose
-methods return values that you don't want to appear in the output.
-Rather than assigning every plugin method call to a dummy variable
-to silence it, you can wrap the block in a null filter:
-
- [% FILTER null;
- USE im = GD.Image(100,100);
- black = im.colorAllocate(0, 0, 0);
- red = im.colorAllocate(255,0, 0);
- blue = im.colorAllocate(0, 0, 255);
- im.arc(50,50,95,75,0,360,blue);
- im.fill(50,50,red);
- im.png | stdout(1);
- END;
- -%]
-
-Notice the use of the C<stdout> filter to ensure that a particular expression
-generates output to C<STDOUT> (in this case in binary mode).
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Internals
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Internals - Template Toolkit internals
-
-=head1 Introduction
-
-This section of the documentation is aimed at developers wishing to
-know more about how the Template Toolkit works on the inside in order
-to extend or adapt it to their own needs.
-
-If that doesn't sound like you then you probably don't need to read this.
-There is no test afterwards.
-
-=head1 Outside Looking In
-
-The L<Template> module is simply a front end module which creates and
-uses a L<Template::Service> and pipes the output wherever you want it to
-go (C<STDOUT> by default, or maybe a file, scalar, etc). The
-C<Apache::Template> module (available separately from CPAN) is another
-front end. That creates a C<Template::Service::Apache> object, calls on
-it as required and sends the output back to the relevant
-C<Apache::Request> object.
-
-These front-end modules are really only there to handle any specifics
-of the environment in which they're being used. The C<Apache::Template>
-front end, for example, handles C<Apache::Request> specifics and
-configuration via the F<httpd.conf>. The regular L<Template> front-end
-deals with C<STDOUT>, variable refs, etc. Otherwise it is
-L<Template::Service> (or subclass) which does all the work.
-
-The L<Template::Service> module provides a high-quality template
-delivery service, with bells, whistles, signed up service level
-agreement and a 30-day no quibble money back guarantee. "Have
-a good time, all the time", that's our motto.
-
-Within the lower levels of the Template Toolkit, there are lots of messy
-details that we generally don't want to have to worry about most of the time.
-Things like templates not being found, or failing to parse correctly, uncaught
-exceptions being thrown, missing plugin modules or dependencies, and so on.
-L<Template::Service> hides that all away and makes everything look simple to
-the outsider. It provides extra features, like C<PRE_PROCESS>, C<PROCESS> and
-C<POST_PROCESS>, and also provides the error recovery mechanism via C<ERROR>.
-You ask it to process a template and it takes care of everything for you. The
-C<Template::Service::Apache> module goes a little bit further, adding some extra
-headers to the L<Apache::Request>, setting a few extra template variables, and so
-on.
-
-For the most part, the job of a service is really just one of scheduling and
-dispatching. It receives a request in the form of a call to its
-L<process()|Template::Service#process()> method and schedules the named
-template specified as an argument, and possibly several other templates
-(C<PRE_PROCESS>, etc) to be processed in order. It doesn't actually process
-the templates itself, but instead makes a
-L<process()|Template::Context#process()> call against a L<Template::Context>
-object.
-
-L<Template::Context> is the runtime engine for the Template Toolkit -
-the module that hangs everything together in the lower levels of the
-Template Toolkit and that one that does most of the real work, albeit
-by crafty delegation to various other friendly helper modules.
-
-Given a template name (or perhaps a reference to a scalar or file
-handle) the context process() method must load and compile, or fetch a
-cached copy of a previously compiled template, corresponding to that
-name. It does this by calling on a list of one or more
-L<Template::Provider> objects (the C<LOAD_TEMPLATES> posse) who themselves
-might get involved with a L<Template::Parser> to help turn source
-templates into executable Perl code (but more on that later).
-
-Thankfully, all of this complexity is hidden away behind a simple
-L<template()|Template::Context#template()> method. You call it passing a
-template name as an argument, and it returns a compiled template in the form
-of a L<Template::Document> object, or otherwise raises an exception.
-
-A L<Template::Document> is a thin object wrapper around a compiled template
-subroutine. The object implements a L<process()|Template::Document#process()>
-method which performs a little bit of housekeeping and then calls the template
-subroutine. The object also defines template metadata (defined in C<[% META
-... %]> directives) and has a L<block()|Template::Document#block()> method
-which returns a hash of any additional C<[% BLOCK xxxx %]> definitions found
-in the template source.
-
-So the context fetches a compiled document via its own
-L<template()|Template::Context#template()> method and then gets ready to
-process it. It first updates the stash (the place where template variables get
-defined - more on that shortly) to set any template variable definitions
-specified as the second argument by reference to hash array. Then, it calls
-the document L<process()|Template::Document#process()> method, passing a
-reference to itself, the context object, as an argument. In doing this, it
-provides itself as an object against which template code can make callbacks to
-access runtime resources and Template Toolkit functionality.
-
-What we're trying to say here is this: not only does the L<Template::Context>
-object receive calls from the I<outside>, i.e. those originating in user
-code calling the process() method on a Template object, but it also
-receives calls from the I<inside>, i.e. those originating in template
-directives of the form C<[% PROCESS template %]>.
-
-Before we move on to that, here's a simple structure diagram showing
-the outer layers of the Template Toolkit heading inwards, with pseudo
-code annotations showing a typical invocation sequence.
-
- ,--------.
- | Caller | use Template;
- `--------' my $tt = Template->new( ... );
- | $tt->process($template, \%vars);
- | Outside
- - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - T T
- | package Template; Inside
- V
- +----------+ sub process($template, \%vars) {
- | Template | $out = $self->SERVICE->process($template, $vars);
- +----------+ print $out or send it to $self->OUTPUT;
- | }
- |
- | package Template::Service;
- |
- | sub process($template, \%vars) {
- | try {
- +----------+ foreach $p in @self->PRE_PROCESS
- | Service | $self->CONTEXT->process($p, $vars);
- +----------+
- | $self->CONTEXT->process($template, $vars);
- |
- | foreach $p @self->POST_PROCESS
- | $self->CONTEXT->process($p, $vars);
- | }
- | catch {
- | $self->CONTEXT->process($self->ERROR);
- | }
- | }
- |
- V package Template::Context;
- +----------+
- | Context | sub process($template, \%vars) {
- +----------+ # fetch compiled template
- | $template = $self->template($template)
- | # update stash
- | $self->STASH->update($vars);
- | # process template
- | $template->process($self)
- | }
- V
- +----------+ package Template::Document;
- | Document |
- +----------+ sub process($context) {
- $output = &{ $self->BLOCK }($context);
- }
-
-=head1 Inside Looking Out
-
-To understand more about what's going on in these lower levels, we
-need to look at what a compiled template looks like. In fact, a
-compiled template is just a regular Perl sub-routine. Here's a very
-simple one.
-
- sub my_compiled_template {
- return "This is a compiled template.\n";
- }
-
-You're unlikely to see a compiled template this simple unless you
-wrote it yourself but it is entirely valid. All a template subroutine
-is obliged to do is return some output (which may be an empty of
-course). If it can't for some reason, then it should raise an error
-via C<die()>.
-
- sub my_todo_template {
- die "This template not yet implemented\n";
- }
-
-If it wants to get fancy, it can raise an error as a
-L<Template::Exception> object. An exception object is really just a
-convenient wrapper for the 'C<type>' and 'C<info>' fields.
-
- sub my_solilique_template {
- die (Template::Exception->new('yorrick', 'Fellow of infinite jest'));
- }
-
-Templates generally need to do a lot more than just generate static output or
-raise errors. They may want to inspect variable values, process another
-template, load a plugin, run a filter, and so on. Whenever a template
-subroutine is called, it gets passed a reference to a L<Template::Context>
-object. It is through this context object that template code can access the
-features of the Template Toolkit.
-
-We described earlier how the L<Template::Service> object calls on
-L<Template::Context> to handle a L<process()|Template::Context#process()>
-request from the I<outside>. We can make a similar request on a context to
-process a template, but from within the code of another template. This is a
-call from the I<inside>.
-
- sub my_process_template {
- my $context = shift;
- my $output = $context->process('header', { title => 'Hello World' })
- . "\nsome content\n"
- . $context->process('footer');
- }
-
-This is then roughly equivalent to a source template something
-like this:
-
- [% PROCESS header
- title = 'Hello World'
- %]
- some content
- [% PROCESS footer %]
-
-Template variables are stored in, and managed by a L<Template::Stash> object.
-This is a blessed hash array in which template variables are defined. The
-object wrapper provides L<get()|Template::Stash#get()> and
-L<set()|Template::Stash#set()> method which implement all the
-I<magical.variable.features> of the Template Toolkit.
-
-Each context object has its own stash, a reference to which can be returned by
-the appropriately named L<stash()|Template::Context#stash()> method. So to
-print the value of some template variable, or for example, to represent the
-following source template:
-
- <title>[% title %]</title>
-
-we might have a subroutine definition something like this:
-
- sub {
- my $context = shift;
- my $stash = $context->stash();
- return '<title>' . $stash->get('title') . '</title>';
- }
-
-The stash L<get()|Template::Stash#get()> method hides the details of the
-underlying variable types, automatically calling code references, checking
-return values, and performing other such tricks. If 'C<title>' happens to be
-bound to a subroutine then we can specify additional parameters as a list
-reference passed as the second argument to get().
-
- [% title('The Cat Sat on the Mat') %]
-
-This translates to the stash call:
-
- $stash->get([ 'title', ['The Cat Sat on the Mat'] ]);
-
-Dotted compound variables can be requested by passing a single
-list reference to the C<get()> method in place of the variable
-name. Each pair of elements in the list should correspond to the
-variable name and reference to a list of arguments for each
-dot-delimited element of the variable.
-
- [% foo(1, 2).bar(3, 4).baz(5) %]
-
-is thus equivalent to
-
- $stash->get([ foo => [1,2], bar => [3,4], baz => [5] ]);
-
-If there aren't any arguments for an element, you can specify an
-empty, zero or null argument list.
-
- [% foo.bar %]
- $stash->get([ 'foo', 0, 'bar', 0 ]);
-
-The L<set()|Template::Stash#set()> method works in a similar way. It takes a
-variable name and a variable value which should be assigned to it.
-
- [% x = 10 %]
- $stash->set('x', 10);
-
- [% x.y = 10 %]
- $stash->set([ 'x', 0, 'y', 0 ], 10);
-
-So the stash gives us access to template variables and the context provides
-the higher level functionality.
-
-Alongside the L<process()|Template::Context#process()> method lies the
-L<include()|Template::Context#include()> method. Just as with the C<PROCESS> /
-C<INCLUDE> directives, the key difference is in variable localisation. Before
-processing a template, the C<process()> method simply updates the stash to set
-any new variable definitions, overwriting any existing values. In contrast,
-the C<include()> method creates a copy of the existing stash, in a process known
-as I<cloning> the stash, and then uses that as a temporary variable store. Any
-previously existing variables are still defined, but any changes made to
-variables, including setting the new variable values passed aas arguments will
-affect only the local copy of the stash (although note that it's only a
-shallow copy, so it's not foolproof). When the template has been processed,
-the C<include()> method restores the previous variable state by I<decloning> the
-stash.
-
-The context also provides an L<insert()|Template::Context#insert()> method to
-implement the C<INSERT> directive, but no C<wrapper()> method. This functionality
-can be implemented by rewriting the Perl code and calling C<include()>.
-
- [% WRAPPER foo -%]
- blah blah [% x %]
- [%- END %]
-
- $context->include('foo', {
- content => 'blah blah ' . $stash->get('x'),
- });
-
-Other than the template processing methods C<process()>, C<include()> and
-C<insert()>, the context defines methods for fetching plugin objects,
-L<plugin()|Template::Context#plugin()>, and filters,
-L<filter()|Template::Context#filter()>.
-
- # TT USE directive
- [% USE foo = Bar(10) %]
-
- # equivalent Perl
- $stash->set('foo', $context->plugin('Bar', [10]));
-
- # TT FILTER block
- [% FILTER bar(20) %]
- blah blah blah
- [% END %]
-
- # equivalent Perl
- my $filter = $context->filter('bar', [20]);
- &$filter('blah blah blah');
-
-Pretty much everything else you might want to do in a template can be done in
-Perl code. Things like C<IF>, C<UNLESS>, C<FOREACH> and so on all have direct
-counterparts in Perl.
-
- # TT IF directive
- [% IF msg %]
- Message: [% msg %]
- [% END %];
-
- # equivalent Perl
- if ($stash->get('msg')) {
- $output .= 'Message: ';
- $output .= $stash->get('msg');
- }
-
-The best way to get a better understanding of what's going on underneath
-the hood is to set the C<$Template::Parser::DEBUG> flag to a true value
-and start processing templates. This will cause the parser to print the
-generated Perl code for each template it compiles to C<STDERR>. You'll
-probably also want to set the C<$Template::Directive::PRETTY> option to
-have the Perl pretty-printed for human consumption.
-
- use Template;
- use Template::Parser;
- use Template::Directive;
-
- $Template::Parser::DEBUG = 1;
- $Template::Directive::PRETTY = 1;
-
- my $template = Template->new();
- $template->process(\*DATA, { cat => 'dog', mat => 'log' });
-
- __DATA__
- The [% cat %] sat on the [% mat %]
-
-The output sent to C<STDOUT> remains as you would expect:
-
- The dog sat on the log
-
-The output sent to C<STDERR> would look something like this:
-
- compiled main template document block:
- sub {
- my $context = shift || die "template sub called without context\n";
- my $stash = $context->stash;
- my $output = '';
- my $error;
-
- eval { BLOCK: {
- $output .= "The ";
- $output .= $stash->get('cat');
- $output .= " sat on the ";
- $output .= $stash->get('mat');
- $output .= "\n";
- } };
- if ($@) {
- $error = $context->catch($@, \$output);
- die $error unless $error->type eq 'return';
- }
-
- return $output;
- }
-
-=head1 Hacking on the Template Toolkit
-
-Please feel free to hack on the Template Toolkit. If you find a bug
-that needs fixing, if you have an idea for something that's missing,
-or you feel inclined to tackle something on the TODO list, then by all
-means go ahead and do it!
-
-If you're contemplating something non-trivial then you'll probably
-want to bring it up on the mailing list first to get an idea about the
-current state of play, find out if anyone's already working on it, and
-so on.
-
-The source code repository for the Template Toolkit is hosted at Github.
-
- https://github.com/abw/Template2
-
-Clone the repository, make your changes, commit them, then send a pull
-request.
-
-Once you've made your changes, please remember to update the test
-suite by adding extra tests to one of the existing test scripts in
-the C<t> sub-directory, or by adding a new test script of your own.
-And of course, run C<make test> to ensure that all the tests pass
-with your new code.
-
-Don't forget that any files you do add will need to be added to the
-MANIFEST. Running C<make manifest> will do this for you, but you need
-to make sure you haven't got any other temporary files lying around
-that might also get added to it.
-
-Documentation is often something that gets overlooked but it's just as
-important as the code. If you're adding a new module, a plugin module, for
-example, then it's OK to include the POD documentation in with the module, but
-I<please> write it all in one piece at the end of the file, I<after> the code
-(just look at any other C<Template::*> module for an example). It's a
-religious issue, I know, but I have a strong distaste for POD documentation
-interspersed throughout the code. In my not-so-humble opinion, it makes both
-the code and the documentation harder to read (same kinda problem as embedding
-Perl in HTML).
-
-Then add a line to the Changes file giving a very brief description of what
-you've done. There's no need to go into detail here (save that for the commit
-message, comments in code or docuemtation where appropriate).
-
-Please also make sure you add your name to the lib/Template/Manual/Credits.pod
-file (if it isn't already there).
-
-Then commit your changes and send a pull request.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Intro
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2014 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Intro - Introduction to the Template Toolkit
-
-=head1 Introduction
-
-The Template Toolkit is a collection of Perl modules which implement a
-fast, flexible, powerful and extensible template processing system.
-It is most often used for generating dynamic web content, although it can
-be used equally well for processing any kind of text documents.
-
-At the simplest level it provides an easy way to process template
-files, filling in embedded variable references with their equivalent
-values. Here's an example of a template.
-
- Dear [% name %],
-
- It has come to our attention that your account is in
- arrears to the sum of [% debt %].
-
- Please settle your account before [% deadline %] or we
- will be forced to revoke your Licence to Thrill.
-
- The Management.
-
-By default, template directives are embedded within the character
-sequences C<[%> ... C<%]> but you can change these and various other
-options to configure how the Template Toolkit looks, feels and works.
-You can set the C<INTERPOLATE> option, for example, if you prefer to
-embed your variables in Perl style:
-
- Dear $name,
-
- It has come to our attention that your account is in
- arrears to the sum of $debt.
-
- ...etc...
-
-=head1 The Template Perl Module
-
-The L<Template> Perl module is the front end to the Template Toolkit for Perl
-programmers, providing access to the full range of functionality through a
-single module with a simple interface. It loads the other modules as required
-and instantiates a default set of objects to handle subsequent template
-processing requests. Configuration parameters may be passed to the L<Template>
-constructor method, L<new()|Template#new()>, which are then used to
-configure the generate object.
-
- use Template;
-
- my $tt = Template->new({
- INCLUDE_PATH => '/usr/local/templates',
- INTERPOLATE => 1,
- }) || die "$Template::ERROR\n";
-
-The L<Template> object implements a L<process()|Template#process()> method for
-processing template files or text. The name of the input template (or various
-other sources) is passed as the first argument, followed by a reference to a
-hash array of variable definitions for substitution in the template.
-
- my $vars = {
- name => 'Count Edward van Halen',
- debt => '3 riffs and a solo',
- deadline => 'the next chorus',
- };
-
- $tt->process('letters/overdrawn', $vars)
- || die $tt->error(), "\n";
-
-The L<process()|Template#process()> method returns a true value (C<1>) on success
-and prints the template output to C<STDOUT>, by default. On error, the
-L<process()|Template#process()> method returns a false value (C<undef>).
-The L<error()|Template#error()> method can then be called to retrieve
-details of the error.
-
-=head1 Component Based Content Construction
-
-A number of special directives are provided, such as C<INSERT>, C<INCLUDE> and
-C<PROCESS>, which allow content to be built up from smaller template
-components. This permits a modular approach to building a web site or other
-content repository, promoting reusability, cross-site consistency, ease of
-construction and subsequent maintenance. Common elements such as headers,
-footers, menu bars, tables, and so on, can be created as separate template
-files which can then be processed into other documents as required. All
-defined variables are inherited by these templates along with any additional
-"local" values specified.
-
- [% PROCESS header
- title = "The Cat Sat on the Mat"
- %]
-
- [% PROCESS menu %]
-
- The location of the missing feline has now been established.
- Thank you for your assistance.
-
- [% INSERT legal/disclaimer %]
-
- [% PROCESS footer %]
-
-You can also define a template as a BLOCK within the same file and
-PROCESS it just like any other template file. This can be invaluable
-for building up repetitive elements such as tables, menus, etc.
-
- [% BLOCK tabrow %]
- <tr><td>[% name %]</td><td>[% email %]</td></tr>
- [% END %]
-
- <table>
- [% PROCESS tabrow name="tom" email="tom@here.org" %]
- [% PROCESS tabrow name="dick" email="disk@there.org" %]
- [% PROCESS tabrow name="larry" email="larry@where.org" %]
- </table>
-
-=head1 Data and Code Binding
-
-One of the key features that sets the Template Toolkit apart from
-other template processors is the ability to bind template variables to
-any kind of Perl data: scalars, lists, hash arrays, sub-routines and
-objects.
-
- my $vars = {
- root => 'http://here.com/there',
- menu => [ 'modules', 'authors', 'scripts' ],
- client => {
- name => 'Doctor Joseph von Satriani',
- id => 'JVSAT',
- },
- checkout => sub { my $total = shift; ...; return $something },
- shopcart => My::Cool::Shopping::Cart->new(),
- };
-
-The Template Toolkit will automatically Do The Right Thing to access the data
-in an appropriate manner to return some value which can then be output. The
-dot operator 'C<.>' is used to access into lists and hashes or to call object
-methods. The C<FOREACH> directive is provided for iterating through lists, and
-various logical tests are available using directives such as C<IF>, C<UNLESS>,
-C<ELSIF>, C<ELSE>, C<SWITCH>, C<CASE>, etc.
-
- [% FOREACH section = menu %]
- <a href="[% root %]/[% section %]/index.html">[% section %]</a>
- [% END %]
-
- <b>Client</b>: [% client.name %] (id: [% client.id %])
-
- [% IF shopcart.nitems %]
- Your shopping cart contains the following items:
- <ul>
- [% FOREACH item = shopcart.contents %]
- <li>[% item.name %] : [% item.qty %] @ [% item.price %]
- [% END %]
- </ul>
-
- [% checkout(shopcart.total) %]
-
- [% ELSE %]
- No items currently in shopping cart.
- [% END %]
-
-=head1 Advanced Features: Filters, Macros, Exceptions, Plugins
-
-The Template Toolkit also provides a number of additional directives
-for advanced processing and programmatical functionality. It supports
-output filters (FILTER), allows custom macros to be defined (MACRO),
-has a fully-featured exception handling system (TRY, THROW, CATCH,
-FINAL) and supports a plugin architecture (USE) which allows special
-plugin modules and even regular Perl modules to be loaded and used
-with the minimum of fuss. The Template Toolkit is "just" a template
-processor but you can trivially extend it to incorporate the
-functionality of any Perl module you can get your hands on. Thus, it
-is also a scalable and extensible template framework, ideally suited
-for managing the presentation layer for application servers, content
-management systems and other web applications.
-
-=head1 Separating Presentation and Application Logic
-
-Rather than embedding Perl code or some other scripting language
-directly into template documents, it encourages you to keep functional
-components (i.e. Perl code) separate from presentation components
-(e.g. HTML templates). The template variables provide the interface
-between the two layers, allowing data to be generated in code and then
-passed to a template component for displaying (pipeline model) or for
-sub-routine or object references to be bound to variables which can
-then be called from the template as and when required (callback
-model).
-
-The directives that the Template Toolkit provide implement their own
-mini programming language, but they're not really designed for
-serious, general purpose programming. Perl is a far more appropriate
-language for that. If you embed application logic (e.g. Perl or other
-scripting language fragments) in HTML templates then you risk losing
-the clear separation of concerns between functionality and
-presentation. It becomes harder to maintain the two elements in
-isolation and more difficult, if not impossible, to reuse code or
-presentation elements by themselves. It is far better to write your
-application code in separate Perl modules, libraries or scripts and
-then use templates to control how the resulting data is presented as
-output. Thus you should think of the Template Toolkit language as a
-set of layout directives for displaying data, not calculating it.
-
-Having said that, the Template Toolkit doesn't force you into one
-approach or the other. It attempts to be pragmatic rather than
-dogmatic in allowing you to do whatever best gets the job done.
-Thus, if you enable the EVAL_PERL option then you can happily embed
-real Perl code in your templates within PERL ... END directives.
-
-=head1 Performance
-
-The Template Toolkit uses a fast YACC-like parser which compiles
-templates into Perl code for maximum runtime efficiency. It also has
-an advanced caching mechanism which manages in-memory and on-disk
-(i.e. persistent) versions of compiled templates. The modules that
-comprise the toolkit are highly configurable and the architecture
-around which they're built is designed to be extensible. The Template
-Toolkit provides a powerful framework around which content creation
-and delivery systems can be built while also providing a simple
-interface through the Template front-end module for general use.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Plugins
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Plugins - Standard plugins
-
-=head1 TEMPLATE TOOLKIT PLUGINS
-
-The following plugin modules are distributed with the Template
-Toolkit. Some of the plugins interface to external modules (detailed
-below) which should be downloaded from any CPAN site and installed
-before using the plugin.
-
-=head2 Assert
-
-New in 2.20! The L<Assert|Template::Plugin::Assert> plugin adds an
-C<assert> virtual method that you can use to catch undefined values.
-
-For example, consider this dotop:
-
- [% user.name %]
-
-If C<user.name> is an undefined value then TT will silently ignore the
-fact and print nothing. If you C<USE> the C<assert> plugin then you
-can add the C<assert> vmethod between the C<user> and C<name> elements,
-like so:
-
- [% user.assert.name %]
-
-Now, if C<user.name> is an undefined value, an exception will be thrown:
-
- assert error - undefined value for name
-
-=head2 CGI
-
-The L<CGI|Template::Plugin::CGI> plugin is a wrapper around Lincoln Stein's
-CGI.pm module. The plugin is distributed with the Template Toolkit (see
-L<Template::Plugin::CGI>) and the L<CGI> module itself is distributed with
-recent versions Perl, or is available from CPAN.
-
- [% USE CGI %]
- [% CGI.param('param_name') %]
- [% CGI.start_form %]
- [% CGI.popup_menu( Name => 'color',
- Values => [ 'Green', 'Brown' ] ) %]
- [% CGI.end_form %]
-
-=head2 Datafile
-
-Provides an interface to data stored in a plain text file in a simple
-delimited format. The first line in the file specifies field names
-which should be delimiter by any non-word character sequence.
-Subsequent lines define data using the same delimiter as in the first
-line. Blank lines and comments (lines starting '#') are ignored. See
-L<Template::Plugin::Datafile> for further details.
-
-/tmp/mydata:
-
- # define names for each field
- id : email : name : tel
- # here's the data
- fred : fred@here.com : Fred Smith : 555-1234
- bill : bill@here.com : Bill White : 555-5678
-
-example:
-
- [% USE userlist = datafile('/tmp/mydata') %]
-
- [% FOREACH user = userlist %]
- [% user.name %] ([% user.id %])
- [% END %]
-
-=head2 Date
-
-The L<Date|Template::Plugin::Date> plugin provides an easy way to generate
-formatted time and date strings by delegating to the L<POSIX> C<strftime()>
-routine. See L<Template::Plugin::Date> and L<POSIX> for further details.
-
- [% USE date %]
- [% date.format %] # current time/date
-
- File last modified: [% date.format(template.modtime) %]
-
-=head2 Directory
-
-The L<Directory|Template::Plugin::Directory> plugin provides a simple
-interface to a directory and the files within it. See
-L<Template::Plugin::Directory> for further details.
-
- [% USE dir = Directory('/tmp') %]
- [% FOREACH file = dir.files %]
- # all the plain files in the directory
- [% END %]
- [% FOREACH file = dir.dirs %]
- # all the sub-directories
- [% END %]
-
-=head2 DBI
-
-The C<DBI> plugin is no longer distributed as part of the Template Toolkit
-(as of version 2.15). It is now available as a separate L<Template::DBI>
-distribution from CPAN.
-
-=head2 Dumper
-
-The L<Dumper|Template::Plugin::Dumper> plugin provides an interface to the
-Data::Dumper module. See L<Template::Plugin::Dumper> and L<Data::Dumper> for
-further details.
-
- [% USE dumper(indent=0, pad="<br>") %]
- [% dumper.dump(myvar, yourvar) %]
-
-=head2 File
-
-The L<File|Template::Plugin::File> plugin provides a general abstraction for
-files and can be used to fetch information about specific files within a
-filesystem. See L<Template::Plugin::File> for further details.
-
- [% USE File('/tmp/foo.html') %]
- [% File.name %] # foo.html
- [% File.dir %] # /tmp
- [% File.mtime %] # modification time
-
-=head2 Filter
-
-This module implements a base class plugin which can be subclassed
-to easily create your own modules that define and install new filters.
-
- package MyOrg::Template::Plugin::MyFilter;
-
- use Template::Plugin::Filter;
- use base qw( Template::Plugin::Filter );
-
- sub filter {
- my ($self, $text) = @_;
- # ...mungify $text...
- return $text;
- }
-
-Example of use:
-
- # now load it...
- [% USE MyFilter %]
-
- # ...and use the returned object as a filter
- [% FILTER $MyFilter %]
- ...
- [% END %]
-
-See L<Template::Plugin::Filter> for further details.
-
-=head2 Format
-
-The L<Format|Template::Plugin::Format> plugin provides a simple way to format
-text according to a C<printf()>-like format. See L<Template::Plugin::Format> for
-further details.
-
- [% USE bold = format('<b>%s</b>') %]
- [% bold('Hello') %]
-
-=head2 GD
-
-The C<GD> plugins are no longer part of the core Template Toolkit distribution.
-They are now available from CPAN in a separate L<Template::GD> distribution.
-
-=head2 HTML
-
-The L<HTML|Template::Plugin::HTML> plugin is very basic, implementing a few
-useful methods for generating HTML. It is likely to be extended in the future
-or integrated with a larger project to generate HTML elements in a generic way.
-
- [% USE HTML %]
- [% HTML.escape("if (a < b && c > d) ..." %]
- [% HTML.attributes(border => 1, cellpadding => 2) %]
- [% HTML.element(table => { border => 1, cellpadding => 2 }) %]
-
-See L<Template::Plugin::HTML> for further details.
-
-=head2 Iterator
-
-The L<Iterator|Template::Plugin::Iterator> plugin provides a way to create a
-L<Template::Iterator> object to iterate over a data set. An iterator is
-created automatically by the C<FOREACH> directive and is aliased to the C<loop>
-variable. This plugin allows an iterator to be explicitly created with a given
-name, or the default plugin name, C<iterator>. See
-L<Template::Plugin::Iterator> for further details.
-
- [% USE iterator(list, args) %]
-
- [% FOREACH item = iterator %]
- [% '<ul>' IF iterator.first %]
- <li>[% item %]
- [% '</ul>' IF iterator.last %]
- [% END %]
-
-=head2 Pod
-
-This plugin provides an interface to the L<Pod::POM|Pod::POM> module
-which parses POD documents into an internal object model which can
-then be traversed and presented through the Template Toolkit.
-
- [% USE Pod(podfile) %]
-
- [% FOREACH head1 = Pod.head1;
- FOREACH head2 = head1/head2;
- ...
- END;
- END
- %]
-
-=head2 Scalar
-
-The Template Toolkit calls user-defined subroutines and object methods
-using Perl's array context by default.
-
- # TT2 calls object methods in array context by default
- [% object.method %]
-
-This plugin module provides a way for you to call subroutines and methods
-in scalar context.
-
- [% USE scalar %]
-
- # force it to use scalar context
- [% object.scalar.method %]
-
- # also works with subroutine references
- [% scalar.my_sub_ref %]
-
-=head2 String
-
-The L<String|Template::Plugin::String> plugin implements an object-oriented
-interface for manipulating strings. See L<Template::Plugin::String> for
-further details.
-
- [% USE String 'Hello' %]
- [% String.append(' World') %]
-
- [% msg = String.new('Another string') %]
- [% msg.replace('string', 'text') %]
-
- The string "[% msg %]" is [% msg.length %] characters long.
-
-=head2 Table
-
-The L<Table|Template::Plugin::Table> plugin allows you to format a list of
-data items into a virtual table by specifying a fixed number of rows or
-columns, with an optional overlap. See L<Template::Plugin::Table> for further
-details.
-
- [% USE table(list, rows=10, overlap=1) %]
-
- [% FOREACH item = table.col(3) %]
- [% item %]
- [% END %]
-
-=head2 URL
-
-The L<URL|Template::Plugin::URL> plugin provides a simple way of constructing
-URLs from a base part and a variable set of parameters. See
-L<Template::Plugin::URL> for further details.
-
- [% USE mycgi = url('/cgi-bin/bar.pl', debug=1) %]
-
- [% mycgi %]
- # ==> /cgi/bin/bar.pl?debug=1
-
- [% mycgi(mode='submit') %]
- # ==> /cgi/bin/bar.pl?mode=submit&debug=1
-
-=head2 Wrap
-
-The L<Wrap|Template::Plugin::Wrap> plugin uses the L<Text::Wrap> module to
-provide simple paragraph formatting. See L<Template::Plugin::Wrap> and
-L<Text::Wrap> for further details.
-
- [% USE wrap %]
- [% wrap(mytext, 40, '* ', ' ') %] # use wrap sub
- [% mytext FILTER wrap(40) -%] # or wrap FILTER
-
-The C<Text::Wrap> module is available from CPAN:
-
- http://www.cpan.org/modules/by-module/Text/
-
-=head2 XML
-
-The C<XML::DOM>, C<XML::RSS>, C<XML::Simple> and C<XML::XPath> plugins are no
-longer distributed with the Template Toolkit as of version 2.15
-
-They are now available in a separate L<Template::XML> distribution.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Syntax
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Syntax - Directive syntax, structure and semantics
-
-=head1 Tag Styles
-
-Template directives are embedded between start and end markers tags.
-By default these tag markers are C<[%> and C<%]>.
-
- [% PROCESS header %]
-
- <h1>Hello World!</h1>
- <a href="[% page.next %]"><img src="[% icon.next %].gif"></a>
-
- [% PROCESS footer %]
-
-You can change the tag characters using the C<START_TAG>, C<END_TAG> and
-C<TAG_STYLE> configuration options. You can also use the C<TAGS> directive to
-define a new tag style for the current template file.
-
-You can also set the C<INTERPOLATE> option to allow simple variable references
-to be embedded directly in templates, prefixed by a C<$>.
-
- # INTERPOLATE = 0
- <td>[% name %]</td>
- <td>[% email %]</td>
-
- # INTERPOLATE = 1
- <td>$name</td>
- <td>$email</td>
-
-Directives may be embedded anywhere in a line of text and can be split
-across several lines. Insignificant whitespace is generally ignored
-within the directive.
-
- [% INCLUDE header
- title = 'Hello World'
- bgcol = '#ffffff'
- %]
-
- [%INCLUDE menu align='right'%]
-
- Name: [% name %] ([%id%])
-
-=head1 Outline Tags
-
-As of version 2.26, the Template Toolkit supports "outline" tags. These have
-a designated marker at the start of a line (C<%%> by default) and continue to
-the end of a line. The newline character at the end of the line is discarded
-(aka "chomped").
-
-So rather than writing something like this:
-
- [% IF some.list.size -%]
- <ul>
- [% FOREACH item IN some.list -%]
- <li>[% item.html %]</li>
- [% END -%]
- </ul>
- [% END -%]
-
-You can write it like this instead:
-
- %% IF some.list.size
- <ul>
- %% FOREACH item IN some.list
- <li>[% item.html %]</li>
- %% END
- </ul>
- %% END
-
-Outline tags aren't enabled by default. There are a numbers of ways you can
-enable them. The first is to use the C<TAGS> directive to set the tag style
-to C<outline> in any templates where you want to use them. This will enable
-outline tags from that point on.
-
- [% TAGS outline -%]
- %% INCLUDE header
-
-You can set the C<TAGS> back to the C<default> value at some point later in the
-template if you want to disable them:
-
- [% TAGS default -%]
-
-You can set the C<TAG_STYLE> configuration option if you want then enabled in
-all templates by default. You can always use the C<[% TAGS default %]>
-directive to disable them in any templates or parts of templates if necessary.
-
- my $tt = Template->new({
- TAG_STYLE => 'outline',
- });
-
-The C<OUTLINE_TAG> option allows you to set the outline tag marker to something
-else if you're not a fan of percent signs. Setting this option will
-automatically enable outline tags.
-
- my $tt = Template->new({
- OUTLINE_TAG => '>>',
- });
-
-You can also use the C<TAGS> directive to define your own custom tags (start,
-end and now optionally, outline) for a template or part of a template.
-
- [% TAGS <* *> >> %]
- >> INCLUDE header # outline tag
- Hello <* name *> # inline tag
-
-If you only specify a start and end tag then outline tags will be disabled.
-
- [% TAGS <* *> %] # no outline tags
-
-=head1 Comments
-
-The C<#> character is used to indicate comments within a directive.
-When placed immediately inside the opening directive tag, it causes
-the entire directive to be ignored.
-
- [%# this entire directive is ignored no
- matter how many lines it wraps onto
- %]
-
-In any other position, it causes the remainder of the current line to
-be treated as a comment.
-
- [% # this is a comment
- theta = 20 # so is this
- rho = 30 # <aol>me too!</aol>
- %]
-
-=head1 Chomping Whitespace
-
-You can add C<-> or C<+> to the immediate start or end of a directive
-tag to control the whitespace chomping options. See the C<PRE_CHOMP> and
-C<POST_CHOMP> options for further details.
-
- [% BLOCK foo -%] # remove trailing newline
- This is block foo
- [%- END %] # remove leading newline
-
-=head1 Implicit Directives: GET and SET
-
-The simplest directives are C<GET> and C<SET> which retrieve and update
-variable values respectively. The C<GET> and C<SET> keywords are actually
-optional as the parser is smart enough to see them for what they really are
-(but note the caveat below on using side-effect notation). Thus, you'll
-generally see:
-
- [% SET foo = 10 %]
- [% GET foo %]
-
-written as:
-
- [% foo = 10 %]
- [% foo %]
-
-You can also express simple logical statements as implicit C<GET> directives:
-
- [% title or template.title or 'Default Title' %]
-
- [% mode == 'graphics' ? "Graphics Mode Enabled" : "Text Mode" %]
-
-All other directives should start with a keyword specified in UPPER
-CASE (but see the C<ANYCASE> option). All directives keywords are in
-UPPER CASE to make them visually distinctive and to distinguish them
-from variables of the same name but different case. It is perfectly
-valid, for example, to define a variable called C<stop> which is
-entirely separate from the C<STOP> directive.
-
- [% stop = 'Clackett Lane Bus Depot' %]
-
- The bus will next stop at [% stop %] # variable
-
- [% STOP %] # directive
-
-=head1 Block Directives
-
-Directives such as C<FOREACH>, C<WHILE>, C<BLOCK>, C<FILTER>, etc., mark the
-start of a block which may contain text or other directives up to the matching
-C<END> directive. Blocks may be nested indefinitely. The C<IF>, C<UNLESS>,
-C<ELSIF> and C<ELSE> directives also define blocks and may be grouped together
-in the usual manner.
-
- [% FOREACH item = [ 'foo' 'bar' 'baz' ] %]
- * Item: [% item %]
- [% END %]
-
- [% BLOCK footer %]
- Copyright 2000 [% me %]
- [% INCLUDE company/logo %]
- [% END %]
-
- [% IF foo %]
- [% FOREACH thing = foo.things %]
- [% thing %]
- [% END %]
- [% ELSIF bar %]
- [% INCLUDE barinfo %]
- [% ELSE %]
- do nothing...
- [% END %]
-
-Block directives can also be used in a convenient side-effect notation.
-
- [% INCLUDE userinfo FOREACH user = userlist %]
-
- [% INCLUDE debugtxt msg="file: $error.info"
- IF debugging %]
-
- [% "Danger Will Robinson" IF atrisk %]
-
-versus:
-
- [% FOREACH user = userlist %]
- [% INCLUDE userinfo %]
- [% END %]
-
- [% IF debugging %]
- [% INCLUDE debugtxt msg="file: $error.info" %]
- [% END %]
-
- [% IF atrisk %]
- Danger Will Robinson
- [% END %]
-
-=head1 Capturing Block Output
-
-The output of a directive can be captured by simply assigning the directive
-to a variable.
-
- [% headtext = PROCESS header title="Hello World" %]
-
- [% people = PROCESS userinfo FOREACH user = userlist %]
-
-This can be used in conjunction with the C<BLOCK> directive for defining large
-blocks of text or other content.
-
- [% poem = BLOCK %]
- The boy stood on the burning deck,
- His fleece was white as snow.
- A rolling stone gathers no moss,
- And Keith is sure to follow.
- [% END %]
-
-Note one important caveat of using this syntax in conjunction with side-effect
-notation. The following directive does not behave as might be expected:
-
- [% var = 'value' IF some_condition %] # does not work
-
-In this case, the directive is interpreted as (spacing added for clarity)
-
- [% var = IF some_condition %]
- value
- [% END %]
-
-rather than
-
- [% IF some_condition %]
- [% var = 'value' %]
- [% END %]
-
-The variable is assigned the output of the C<IF> block which returns
-C<'value'> if true, but nothing if false. In other words, the following
-directive will always cause 'var' to be cleared.
-
- [% var = 'value' IF 0 %]
-
-To achieve the expected behaviour, the directive should be written as:
-
- [% SET var = 'value' IF some_condition %]
-
-=head1 Chaining Filters
-
-Multiple C<FILTER> directives can be chained together in sequence. They
-are called in the order defined, piping the output of one into the
-input of the next.
-
- [% PROCESS somefile FILTER truncate(100) FILTER html %]
-
-The pipe character, C<|>, can also be used as an alias for C<FILTER>.
-
- [% PROCESS somefile | truncate(100) | html %]
-
-=head1 Multiple Directive Blocks
-
-Multiple directives can be included within a single tag when delimited
-by semi-colons. Note however that the C<TAGS> directive must always
-be specified in a tag by itself.
-
- [% IF title;
- INCLUDE header;
- ELSE;
- INCLUDE other/header title="Some Other Title";
- END
- %]
-
-versus
-
- [% IF title %]
- [% INCLUDE header %]
- [% ELSE %]
- [% INCLUDE other/header title="Some Other Title" %]
- [% END %]
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::VMethods
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2015 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::VMethods - Virtual Methods
-
-=head1 Scalar Virtual Methods
-
-=head2 chunk(size)
-
-Splits the value into a list of chunks of a certain size.
-
- [% ccard_no = "1234567824683579";
- ccard_no.chunk(4).join
- %]
-
-Output:
-
- 1234 5678 2468 3579
-
-If the size is specified as a negative number then the text will
-be chunked from right-to-left. This gives the correct grouping
-for numbers, for example.
-
- [% number = 1234567;
- number.chunk(-3).join(',')
- %]
-
-Output:
-
- 1,234,567
-
-=head2 collapse
-
-Returns the text with any leading and trailing whitespace removed and any
-internal sequences of whitespace converted to a single space
-
- [% text = " The bird\n is the word" %]
- [% text.collapse %] # The bird is the word
-
-=head2 defined
-
-Returns true if the value is defined.
-
- [% user = get_user(uid) IF uid.defined %]
-
-=head2 dquote
-
-Returns the text with any double quote characters escaped with a backslash
-prefix. Any newline characters in the text will be replaced with "\n".
-
- [% quote = 'He said "Oh really?"' %]
- [% quote.dquote %] # He said \"Oh really?\"
-
-=head2 hash
-
-Return the value as a hash reference containing a single entry with
-the key C<value> indicating the original scalar value. As with the
-C<list> virtual method, this is generally used to help massage data
-into different formats.
-
-=head2 lcfirst
-
-Returns the text with the first letter converted to lower case.
-
- [% word = 'BIRD' %]
- [% word.lcfirst %] # bIRD
-
-=head2 length
-
-Returns the length of the string representation of the item:
-
- [% IF password.length < 8 %]
- Password too short, dumbass!
- [% END %]
-
-=head2 empty
-
-Returns true if the string is empty:
-
- [% IF details.empty %]
- No details specified
- [% END %]
-
-=head2 list
-
-Return the value as a single element list. This can be useful if you
-have a variable which may contain a single item or a list and you want
-to treat them equally. The C<list> method can be called against a list
-reference and will simply return the original reference, effectively
-a no-op.
-
- [% thing.list.size %] # thing can be a scalar or a list
-
-=head2 lower
-
-Returns the text in lower case.
-
- [% word = 'BIRD' %]
- [% word.lower %] # bird
-
-=head2 match(pattern, global)
-
-Performs a regular expression match on the string using the pattern
-passed as an argument. If the pattern matches the string then the
-method returns a reference to a list of any strings captured within
-parenthesis in the pattern.
-
- [% name = 'Larry Wall' %]
- [% matches = name.match('(\w+) (\w+)') %]
- [% matches.1 %], [% matches.0 %] # Wall, Larry
-
-If the pattern does not match then the method returns false, rather
-than returning an empty list which Perl and the Template Toolkit both
-consider to be a true value. This allows you to write expression like
-this.
-
- [% "We're not worthy!" IF name.match('Larry Wall') %]
-
- [% IF (matches = name.match('(\w+) (\w+)')) %]
- pattern matches: [% matches.join(', ') %]
- [% ELSE %]
- pattern does not match
- [% END %]
-
-Any regex modifiers, like C</s>, should be added in the regex using
-the C<(?s)> syntax. For example, to modify the regex to disregard
-whitespace (the C</x> switch), use:
-
- [% re = '(?x)
- (\w+)
- [ ]
- (\w+)
- ';
- matches = name.match(re);
- %]
-
-To perform a global search to match the pattern as many times as it
-appears in the source string, provide a true value for the C<global>
-argument following the pattern.
-
- [% text = 'bandanna';
- text.match('an+', 1).join(', ) # an, ann
- %]
-
-=head2 repeat(n)
-
-Repeat the string a specified number of times.
-
- [% name = 'foo' %]
- [% name.repeat(3) %] # foofoofoo
-
-=head2 replace(search, replace)
-
-Outputs the string with all instances of the first argument (specified
-as a Perl regular expression) with the second.
-
- [% name = 'foo, bar & baz' %]
- [% name.replace('\W+', '_') %] # foo_bar_baz
-
-You can use C<$1>, C<$2>, etc., to reference captured parts (in parentheses)
-in the regular expression. Just be careful to I<single> quote the replacement
-string. If you use I<double> quotes then TT will try and interpolate the
-variables before passing the string to the C<replace> vmethod.
-
- [% name = 'FooBarBaz' %]
- [% name.replace('([A-Z])', ' $1') %] # Foo Bar Baz
-
-=head2 remove(pattern)
-
-Outputs the string with all instances of the pattern (specified
-as a Perl regular expression) removed.
-
- [% name = 'foo, bar & baz' %]
- [% name.remove('\W+') %] # foobarbaz
-
-=head2 search(pattern)
-
-Performs a similar function to L<match> but simply returns true if the
-string matches the regular expression pattern passed as an argument.
-
- [% name = 'foo bar baz' %]
- [% name.search('bar') ? 'bar' : 'no bar' %] # bar
-
-This virtual method is now deprecated in favour of L<match>. Move along
-now, there's nothing more to see here.
-
-=head2 size
-
-Always returns 1 for scalar values. This method is provided for
-consistency with the hash and list size methods.
-
-=head2 split(pattern)
-
-Calls Perl's C<split()> function to split a string into a list of
-strings.
-
- [% FOREACH dir IN mypath.split(':') %]
- [% dir %]
- [% END %]
-
-=head2 substr(offset, length, replacement)
-
-Returns a substring starting at C<offset>, for C<length> characters.
-
- [% str 'foo bar baz wiz waz woz') %]
- [% str.substr(4, 3) %] # bar
-
-If C<length> is not specified then it returns everything from the
-C<offset> to the end of the string.
-
- [% str.substr(12) %] # wiz waz woz
-
-If both C<length> and C<replacement> are specified, then the method
-replaces everything from C<offset> for C<length> characters with
-C<$replacement>. The substring removed from the string is then returned.
-
- [% str.substr(0, 11, 'FOO') %] # foo bar baz
- [% str %] # FOO wiz waz woz
-
-=head2 squote
-
-Returns the text with any single quote characters escaped with a backslash
-prefix.
-
- [% tim = "Tim O'Reilly" %]
- [% tim.squote %] # Tim O\'Reilly
-
-=head2 trim
-
-Returns the text with any leading and trailing whitespace removed.
-
- [% text = ' hello world ' %]
- [% text.trim %] # hello world
-
-=head2 ucfirst
-
-Returns the text with the first letter converted to upper case.
-
- [% word = 'bird' %]
- [% word.ucfirst %] # Bird
-
-=head2 upper
-
-Returns the text in upper case.
-
- [% word = 'bird' %]
- [% word.upper %] # BIRD
-
-=head1 Hash Virtual Methods
-
-=head2 keys
-
-Returns a list of keys in the hash. They are not returned in any
-particular order, but the order is the same as for the corresponding
-values method.
-
- [% FOREACH key IN hash.keys %]
- * [% key %]
- [% END %]
-
-If you want the keys in sorted order, use the list C<sort> method.
-
- [% FOREACH key IN hash.keys.sort %]
- * [% key %]
- [% END %]
-
-Having got the keys in sorted order, you can then use variable
-interpolation to fetch the value. This is shown in the following
-example by the use of C<$key> to fetch the item from C<hash> whose
-key is stored in the C<key> variable.
-
- [% FOREACH key IN hash.keys.sort %]
- * [% key %] = [% hash.$key %]
- [% END %]
-
-Alternately, you can use the C<pairs> method to get a list of
-key/value pairs in sorted order.
-
-=head2 values
-
-Returns a list of the values in the hash. As with the C<keys> method,
-they are not returned in any particular order, although it is the same
-order that the keys are returned in.
-
- [% hash.values.join(', ') %]
-
-=head2 items
-
-Returns a list of both the keys and the values expanded into a single list.
-
- [% hash = {
- a = 10
- b = 20
- };
-
- hash.items.join(', ') # a, 10, b, 20
- %]
-
-=head2 each
-
-This method currently returns the same thing as the C<items> method.
-
-However, please note that this method will change in the next major
-version of the Template Toolkit (v3) to return the same thing as the
-C<pairs> method. This will be done in an effort to make these virtual
-method more consistent with each other and how Perl works.
-
-In anticipation of this, we recommend that you stop using C<hash.each>
-and instead use C<hash.items>.
-
-=head2 pairs
-
-This method returns a list of key/value pairs. They are returned in
-sorted order according to the keys.
-
- [% FOREACH pair IN product.pairs %]
- * [% pair.key %] is [% pair.value %]
- [% END %]
-
-=head2 list
-
-Returns the contents of the hash in list form. An argument can be
-passed to indicate the desired items required in the list: C<keys> to
-return a list of the keys (same as C<hash.keys>), C<values> to return a
-list of the values (same as C<hash.values>), C<each> to return as list
-of key and values (same as C<hash.each>), or C<pairs> to return a list
-of key/value pairs (same as C<hash.pairs>).
-
- [% keys = hash.list('keys') %]
- [% values = hash.list('values') %]
- [% items = hash.list('each') %]
- [% pairs = hash.list('pairs') %]
-
-When called without an argument it currently returns the same thing as
-the C<pairs> method. However, please note that this method will change
-in the next major version of the Template Toolkit (v3) to return a
-reference to a list containing the single hash reference (as per the
-scalar list method).
-
-In anticipation of this, we recommend that you stop using C<hash.list>
-and instead use C<hash.pairs>.
-
-=head2 sort, nsort
-
-Return a list of the keys, sorted alphabetically (C<sort>) or numerically
-(C<nsort>) according to the corresponding values in the hash.
-
- [% FOREACH n IN phones.sort %]
- [% phones.$n %] is [% n %],
- [% END %]
-
-=head2 import
-
-The C<import> method can be called on a hash array to import the contents
-of another hash array.
-
- [% hash1 = {
- foo = 'Foo'
- bar = 'Bar'
- }
- hash2 = {
- wiz = 'Wiz'
- woz = 'Woz'
- }
- %]
-
- [% hash1.import(hash2) %]
- [% hash1.wiz %] # Wiz
-
-You can also call the C<import()> method by itself to import a hash array
-into the current namespace hash.
-
- [% user = { id => 'lwall', name => 'Larry Wall' } %]
- [% import(user) %]
- [% id %]: [% name %] # lwall: Larry Wall
-
-=head2 defined, exists
-
-Returns a true or false value if an item in the hash denoted by the key
-passed as an argument is defined or exists, respectively.
-
- [% hash.defined('somekey') ? 'yes' : 'no' %]
- [% hash.exists('somekey') ? 'yes' : 'no' %]
-
-When called without any argument, C<hash.defined> returns true if the hash
-itself is defined (e.g. the same effect as C<scalar.defined>).
-
-=head2 delete
-
-Delete one or more items from the hash.
-
- [% hash.delete('foo', 'bar') %]
-
-=head2 size
-
-Returns the number of key/value pairs in the hash.
-
-=head2 empty
-
-Returns true if the hash is empty:
-
- [% IF config.empty %]
- No configuration available
- [% END %]
-
-=head2 item
-
-Returns an item from the hash using a key passed as an argument.
-
- [% hash.item('foo') %] # same as hash.foo
-
-=head1 List Virtual Methods
-
-=head2 first, last
-
-Returns the first/last item in the list. The item is not removed from the
-list.
-
- [% results.first %] to [% results.last %]
-
-If either is given a numeric argument C<n>, they return the first or
-last C<n> elements:
-
- The first 5 results are [% results.first(5).join(", ") %].
-
-=head2 size, max
-
-Returns the size of a list (number of elements) and the maximum
-index number (size - 1), respectively.
-
- [% results.size %] search results matched your query
-
-=head2 empty
-
-Returns true if the list is empty:
-
- [% IF results.empty %]
- No results found
- [% END %]
-
-=head2 defined
-
-Returns a true or false value if the item in the list denoted by the
-argument is defined.
-
- [% list.defined(3) ? 'yes' : 'no' %]
-
-When called without any argument, C<list.defined> returns true if the list
-itself is defined (e.g. the same effect as C<scalar.defined>).
-
-=head2 reverse
-
-Returns the items of the list in reverse order.
-
- [% FOREACH s IN scores.reverse %]
- ...
- [% END %]
-
-=head2 join
-
-Joins the items in the list into a single string, using Perl's C<join()>
-function.
-
- [% items.join(', ') %]
-
-=head2 grep
-
-Returns a list of the items in the list that match a regular expression
-pattern.
-
- [% FOREACH directory.files.grep('\.txt$') %]
- ...
- [% END %]
-
-=head2 sort, nsort
-
-Returns the items in alpha (C<sort>) or numerical (C<nsort>) order.
-
- [% library = books.sort %]
-
-An argument can be provided to specify a search key. Where an item in
-the list is a hash reference, the search key will be used to retrieve a
-value from the hash which will then be used as the comparison value.
-Where an item is an object which implements a method of that name, the
-method will be called to return a comparison value.
-
- [% library = books.sort('author') %]
-
-In the example, the C<books> list can contains hash references with
-an C<author> key or objects with an C<author> method.
-
-You can also specify multiple sort keys.
-
- [% library = books.sort('author', 'title') %]
-
-In this case the books will be sorted primarily by author. If two or more
-books have authors with the same name then they will be sorted by title.
-
-=head2 unshift(item), push(item)
-
-The C<push()> method adds an item or items to the end of list.
-
- [% mylist.push(foo) %]
- [% mylist.push(foo, bar) %]
-
-The C<unshift()> method adds an item or items to the start of a list.
-
- [% mylist.unshift(foo) %]
- [% mylist.push(foo, bar) %]
-
-=head2 shift, pop
-
-Removes the first/last item from the list and returns it.
-
- [% first = mylist.shift %]
- [% last = mylist.pop %]
-
-=head2 unique
-
-Returns a list of the unique elements in a list, in the same order
-as in the list itself.
-
- [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
- [% numbers = mylist.unique %]
-
-While this can be explicitly sorted, it is not required that the list
-be sorted before the unique elements are pulled out (unlike the Unix
-command line utility).
-
- [% numbers = mylist.unique.sort %]
-
-=head2 import
-
-Appends the contents of one or more other lists to the end of the
-current list.
-
- [% one = [ 1 2 3 ];
- two = [ 4 5 6 ];
- three = [ 7 8 9 ];
- one.import(two, three);
- one.join(', ); # 1, 2, 3, 4, 5, 6, 7, 8, 9
- %]
-
-=head2 merge
-
-Returns a list composed of zero or more other lists:
-
- [% list_one = [ 1 2 3 ];
- list_two = [ 4 5 6 ];
- list_three = [ 7 8 9 ];
- list_four = list_one.merge(list_two, list_three);
- %]
-
-The original lists are not modified.
-
-=head2 slice(from, to)
-
-Returns a slice of items in the list between the bounds passed as
-arguments. If the second argument, C<to>, isn't specified, then it
-defaults to the last item in the list. The original list is not
-modified.
-
- [% first_three = list.slice(0,2) %]
- [% last_three = list.slice(-3, -1) %]
-
-=head2 splice(offset, length, list)
-
-Behaves just like Perl's C<splice()> function allowing you to selectively
-remove and/or replace elements in a list. It removes C<length> items
-from the list, starting at C<offset> and replaces them with the items
-in C<list>.
-
- [% play_game = [ 'play', 'scrabble' ];
- ping_pong = [ 'ping', 'pong' ];
- redundant = play_game.splice(1, 1, ping_pong);
- redundant.join; # scrabble
- play_game.join; # play ping pong
- %]
-
-The method returns a list of the items removed by the splice.
-You can use the C<CALL> directive to ignore the output if you're
-not planning to do anything with it.
-
- [% CALL play_game.splice(1, 1, ping_pong) %]
-
-As well as providing a reference to a list of replacement values,
-you can pass in a list of items.
-
- [% CALL list.splice(-1, 0, 'foo', 'bar') %]
-
-Be careful about passing just one item in as a replacement value.
-If it is a reference to a list then the contents of the list will
-be used. If it's not a list, then it will be treated as a single
-value. You can use square brackets around a single item if you
-need to be explicit:
-
- [% # push a single item, an_item
- CALL list.splice(-1, 0, an_item);
-
- # push the items from another_list
- CALL list.splice(-1, 0, another_list);
-
- # push a reference to another_list
- CALL list.splice(-1, 0, [ another_list ]);
- %]
-
-=head2 hash
-
-Returns a reference to a hash array comprised of the elements in the
-list. The even-numbered elements (0, 2, 4, etc) become the keys and
-the odd-numbered elements (1, 3, 5, etc) the values.
-
- [% list = ['pi', 3.14, 'e', 2.718] %]
- [% hash = list.hash %]
- [% hash.pi %] # 3.14
- [% hash.e %] # 2.718
-
-If a numerical argument is provided then the hash returned will have
-keys generated for each item starting at the number specified.
-
- [% list = ['beer', 'peanuts'] %]
- [% hash = list.hash(1) %]
- [% hash.1 %] # beer
- [% hash.2 %] # peanuts
-
-=head1 Automagic Promotion of Scalar to List for Virtual Methods
-
-In addition to the scalar virtual methods listed in the previous
-section, you can also call any list virtual method against a scalar.
-The item will be automagically promoted to a single element list and
-the appropriate list virtual method will be called.
-
-One particular benefit of this comes when calling subroutines or
-object methods that return a list of items, rather than the
-preferred reference to a list of items. In this case, the
-Template Toolkit automatically folds the items returned into
-a list.
-
-The upshot is that you can continue to use existing Perl modules or
-code that returns lists of items, without having to refactor it
-just to keep the Template Toolkit happy (by returning references
-to list). C<Class::DBI> module is just one example of a particularly
-useful module which returns values this way.
-
-If only a single item is returned from a subroutine then the
-Template Toolkit assumes it meant to return a single item (rather
-than a list of 1 item) and leaves it well alone, returning the
-single value as it is. If you're executing a database query,
-for example, you might get 1 item returned, or perhaps many
-items which are then folded into a list.
-
-The C<FOREACH> directive will happily accept either a list or a single item
-which it will treat as a list. So it's safe to write directives like this,
-where we assume that the C<something> variable is bound to a subroutine which
-may return one or more items:
-
- [% FOREACH item IN something %]
- ...
- [% END %]
-
-The automagic promotion of scalars to single item lists means
-that you can also use list virtual methods safely, even if you
-only get one item returned. For example:
-
- [% something.first %]
- [% something.join %]
- [% something.reverse.join(', ') %]
-
-Note that this is very much a last-ditch behaviour. If the single
-item return is an object with a C<first> method, for example, then that
-will be called, as expected, in preference to the list virtual method.
-
-=head1 Defining Custom Virtual Methods
-
-You can define your own virtual methods for scalars, lists and hash arrays.
-The L<Template::Stash> package variables C<$SCALAR_OPS>, C<$LIST_OPS> and
-C<$HASH_OPS> are references to hash arrays that define these virtual methods.
-C<HASH_OPS> and C<LIST_OPS> methods are subroutines that accept a hash/list
-reference as the first item. C<SCALAR_OPS> are subroutines that accept a scalar
-value as the first item. Any other arguments specified when the method is
-called will be passed to the subroutine.
-
- # load Template::Stash to make method tables visible
- use Template::Stash;
-
- # define list method to return new list of odd numbers only
- $Template::Stash::LIST_OPS->{ odd } = sub {
- my $list = shift;
- return [ grep { $_ % 2 } @$list ];
- };
-
-Example template:
-
- [% primes = [ 2, 3, 5, 7, 9 ] %]
- [% primes.odd.join(', ') %] # 3, 5, 7, 9
-
-TODO: document the define_vmethod() method which makes this even easier
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Variables
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Variables - Template variables and code bindings
-
-=head1 Template Variables
-
-A reference to a hash array may be passed as the second argument to the
-L<process()|Template#process()> method, containing definitions of template
-variables. The C<VARIABLES> (a.k.a. C<PRE_DEFINE>) option can also be used to
-pre-define variables for all templates processed by the object.
-
- my $tt = Template->new({
- VARIABLES => {
- version => 3.14,
- release => 'Sahara',
- },
- });
-
- my $vars = {
- serial_no => 271828,
- };
-
- $tt->process('myfile', $vars);
-
-F<myfile> template:
-
- This is version [% version %] ([% release %]).
- Serial number: [% serial_no %]
-
-Generated Output:
-
- This is version 3.14 (Sahara)
- Serial number: 271828
-
-Variable names may contain any alphanumeric characters or underscores. They
-may be lower, upper or mixed case although the usual convention is to use
-lower case. The case I<is> significant however, and 'C<foo>', 'C<Foo>' and
-'C<FOO>' are all different variables. Upper case variable names are permitted,
-but not recommended due to a possible conflict with an existing or future
-reserved word. As of version 2.00, these are:
-
- GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
- IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
- USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
- TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
- CLEAR TO STEP AND OR NOT MOD DIV END
-
-The variable values may be of virtually any Perl type, including
-simple scalars, references to lists, hash arrays, subroutines or
-objects. The Template Toolkit will automatically apply the correct
-procedure to accessing these values as they are used in the template.
-
-Example data:
-
- my $vars = {
- article => 'The Third Shoe',
- person => {
- id => 314,
- name => 'Mr. Blue',
- email => 'blue@nowhere.org',
- },
- primes => [ 2, 3, 5, 7, 11, 13 ],
- wizard => sub { return join(' ', 'Abracadabra!', @_) },
- cgi => CGI->new('mode=submit&debug=1'),
- };
-
-Example template:
-
- [% article %]
-
- [% person.id %]: [% person.name %] <[% person.email %]>
-
- [% primes.first %] - [% primes.last %], including [% primes.3 %]
- [% primes.size %] prime numbers: [% primes.join(', ') %]
-
- [% wizard %]
- [% wizard('Hocus Pocus!') %]
-
- [% cgi.param('mode') %]
-
-Generated output:
-
- The Third Shoe
-
- 314: Mr. Blue <blue@nowhere.org>
-
- 2 - 13, including 7
- 6 prime numbers: 2, 3, 5, 7, 11, 13
-
- Abracadabra!
- Abracadabra! Hocus Pocus!
-
- submit
-
-=head2 Scalar Values
-
-Regular scalar variables are accessed by simply specifying their name.
-As these are just entries in the top-level variable hash they can be
-considered special cases of hash array referencing as described below,
-with the main namespace hash automatically implied.
-
- [% article %]
-
-=head2 Hash Array References
-
-Members of hash arrays are accessed by specifying the hash reference
-and key separated by the dot 'C<.>' operator.
-
-Example data:
-
- my $vars = {
- 'home' => 'http://www.myserver.com/homepage.html',
- 'page' => {
- 'this' => 'mypage.html',
- 'next' => 'nextpage.html',
- 'prev' => 'prevpage.html',
- },
- };
-
-Example template:
-
- <a href="[% home %]">Home</a>
- <a href="[% page.prev %]">Previous Page</a>
- <a href="[% page.next %]">Next Page</a>
-
-Generated output:
-
- <a href="http://www.myserver.com/homepage.html">Home</a>
- <a href="prevpage.html">Previous Page</a>
- <a href="nextpage.html">Next Page</a>
-
-Any key in a hash which starts with a 'C<_>' or 'C<.>' character will be
-considered private and cannot be evaluated or updated from within a
-template. The undefined value will be returned for any such variable
-accessed which the Template Toolkit will silently ignore (unless the
-C<DEBUG> option is enabled).
-
-Example data:
-
- my $vars = {
- message => 'Hello World!',
- _secret => "On the Internet, no-one knows you're a dog",
- thing => {
- public => 123,
- _private => 456,
- '.hidden' => 789,
- },
- };
-
-Example template:
-
- [% message %] # outputs "Hello World!"
- [% _secret %] # no output
- [% thing.public %] # outputs "123"
- [% thing._private %] # no output
- [% thing..hidden %] # ERROR: unexpected token (..)
-
-You can disable this feature by setting the C<$Template::Stash::PRIVATE>
-package variable to a false value.
-
- $Template::Stash::PRIVATE = undef; # now you can thing._private
-
-To access a hash entry using a key stored in another variable, prefix
-the key variable with 'C<$>' to have it interpolated before use (see
-L<Variable Interpolation>).
-
- [% pagename = 'next' %]
- [% page.$pagename %] # same as [% page.next %]
-
-When you assign to a variable that contains multiple namespace
-elements (i.e. it has one or more 'C<.>' characters in the name),
-any hashes required to represent intermediate namespaces will be
-created automatically. In this following example, the C<product>
-variable automatically springs into life as a hash array unless
-otherwise defined.
-
- [% product.id = 'XYZ-2000'
- product.desc = 'Bogon Generator'
- product.price = 666
- %]
-
- The [% product.id %] [% product.desc %]
- costs $[% product.price %].00
-
-Generated output:
-
- The XYZ-2000 Bogon Generator
- costs $666.00
-
-You can use Perl's familiar C<{> ... C<}> construct to explicitly create
-a hash and assign it to a variable. Note that commas are optional
-between key/value pairs and C<=> can be used in place of C<=E<gt>>.
-
- # minimal TT style
- [% product = {
- id = 'XYZ-2000'
- desc = 'Bogon Generator'
- price = 666
- }
- %]
-
- # perl style
- [% product = {
- id => 'XYZ-2000',
- desc => 'Bogon Generator',
- price => 666,
- }
- %]
-
-=head2 List References
-
-Items in lists are also accessed by use of the dot operator.
-
-Example data:
-
- my $vars = {
- people => [ 'Tom', 'Dick', 'Larry' ],
- };
-
-Example template:
-
- [% people.0 %] # Tom
- [% people.1 %] # Dick
- [% people.2 %] # Larry
-
-The C<FOREACH> directive can be used to iterate through items in a list.
-
- [% FOREACH person IN people %]
- Hello [% person %]
- [% END %]
-
-Generated output:
-
- Hello Tom
- Hello Dick
- Hello Larry
-
-Lists can be constructed in-situ using the regular anonymous list
-C<[> ... C<]> construct. Commas between items are optional.
-
- [% cols = [ 'red', 'green', 'blue' ] %]
-
- [% FOREACH c IN cols %]
- [% c %]
- [% END %]
-
-or:
-
- [% FOREACH c IN [ 'red', 'green', 'blue' ] %]
- [% c %]
- [% END %]
-
-You can also create simple numerical sequences using the C<..> range
-operator:
-
- [% n = [ 1 .. 4 ] %] # n is [ 1, 2, 3, 4 ]
-
- [% x = 4
- y = 8
- z = [x..y] # z is [ 4, 5, 6, 7, 8 ]
- %]
-
-=head2 Subroutines
-
-Template variables can contain references to Perl subroutines. When
-the variable is used, the Template Toolkit will automatically call the
-subroutine, passing any additional arguments specified. The return
-value from the subroutine is used as the variable value and inserted
-into the document output.
-
- my $vars = {
- wizard => sub { return join(' ', 'Abracadabra!', @_) },
- };
-
-Example template:
-
- [% wizard %] # Abracadabra!
- [% wizard('Hocus Pocus!') %] # Abracadabra! Hocus Pocus!
-
-=head2 Objects
-
-Template variables can also contain references to Perl objects.
-Methods are called using the dot operator to specify the method
-against the object variable. Additional arguments can be specified
-as with subroutines.
-
- use CGI;
-
- my $vars = {
- # hard coded CGI params for purpose of example
- cgi => CGI->new('mode=submit&debug=1'),
- };
-
-Example template:
-
- [% FOREACH p IN cgi.param %] # returns list of param keys
- [% p %] => [% cgi.param(p) %] # fetch each param value
- [% END %]
-
-Generated output:
-
- mode => submit
- debug => 1
-
-Object methods can also be called as lvalues. That is, they can appear on
-the left side of an assignment. The method will be called passing the
-assigning value as an argument.
-
- [% myobj.method = 10 %]
-
-equivalent to:
-
- [% myobj.method(10) %]
-
-=head2 Passing Parameters and Returning Values
-
-Subroutines and methods will be passed any arguments specified in the
-template. Any template variables in the argument list will first be
-evaluated and their resultant values passed to the code.
-
- my $vars = {
- mycode => sub { return 'received ' . join(', ', @_) },
- };
-
-template:
-
- [% foo = 10 %]
- [% mycode(foo, 20) %] # received 10, 20
-
-Named parameters may also be specified. These are automatically collected
-into a single hash array which is passed by reference as the B<last>
-parameter to the sub-routine. Named parameters can be specified using
-either C<=E<gt>> or C<=> and can appear anywhere in the argument list.
-
- my $vars = {
- myjoin => \&myjoin,
- };
-
- sub myjoin {
- # look for hash ref as last argument
- my $params = ref $_[-1] eq 'HASH' ? pop : { };
- return join($params->{ joint } || ' + ', @_);
- }
-
-Example template:
-
- [% myjoin(10, 20, 30) %]
- [% myjoin(10, 20, 30, joint = ' - ' %]
- [% myjoin(joint => ' * ', 10, 20, 30 %]
-
-Generated output:
-
- 10 + 20 + 30
- 10 - 20 - 30
- 10 * 20 * 30
-
-Parenthesised parameters may be added to any element of a variable,
-not just those that are bound to code or object methods. At present,
-parameters will be ignored if the variable isn't "callable" but are
-supported for future extensions. Think of them as "hints" to that
-variable, rather than just arguments passed to a function.
-
- [% r = 'Romeo' %]
- [% r(100, 99, s, t, v) %] # outputs "Romeo"
-
-User code should return a value for the variable it represents. This
-can be any of the Perl data types described above: a scalar, or
-reference to a list, hash, subroutine or object. Where code returns a
-list of multiple values the items will automatically be folded into a
-list reference which can be accessed as per normal.
-
- my $vars = {
- # either is OK, first is recommended
- items1 => sub { return [ 'foo', 'bar', 'baz' ] },
- items2 => sub { return ( 'foo', 'bar', 'baz' ) },
- };
-
-Example template:
-
- [% FOREACH i IN items1 %]
- ...
- [% END %]
-
- [% FOREACH i IN items2 %]
- ...
- [% END %]
-
-=head2 Error Handling
-
-Errors can be reported from user code by calling C<die()>. Errors raised
-in this way are caught by the Template Toolkit and converted to
-structured exceptions which can be handled from within the template.
-A reference to the exception object is then available as the C<error>
-variable.
-
- my $vars = {
- barf => sub {
- die "a sick error has occurred\n";
- },
- };
-
-Example template:
-
- [% TRY %]
- [% barf %] # calls sub which throws error via die()
- [% CATCH %]
- [% error.info %] # outputs "a sick error has occurred\n"
- [% END %]
-
-Error messages thrown via C<die()> are converted to exceptions of type
-C<undef> (the literal string "undef" rather than the undefined value).
-Exceptions of user-defined types can be thrown by calling C<die()> with
-a reference to a L<Template::Exception> object.
-
- use Template::Exception;
-
- my $vars = {
- login => sub {
- ...do something...
- die Template::Exception->new( badpwd => 'password too silly' );
- },
- };
-
-Example template:
-
- [% TRY %]
- [% login %]
- [% CATCH badpwd %]
- Bad password: [% error.info %]
- [% CATCH %]
- Some other '[% error.type %]' error: [% error.info %]
- [% END %]
-
-The exception types C<stop> and C<return> are used to implement the
-C<STOP> and C<RETURN> directives. Throwing an exception as:
-
- die (Template::Exception->new('stop'));
-
-has the same effect as the directive:
-
- [% STOP %]
-
-=head1 Virtual Methods
-
-The Template Toolkit implements a number of "virtual methods" which
-can be applied to scalars, hashes or lists. For example:
-
- [% mylist = [ 'foo', 'bar', 'baz' ] %]
- [% newlist = mylist.sort %]
-
-Here C<mylist> is a regular reference to a list, and 'sort' is
-a virtual method that returns a new list of the items in sorted
-order. You can chain multiple virtual methods together. For
-example:
-
- [% mylist.sort.join(', ') %]
-
-Here the C<join> virtual method is called to join the sorted list into
-a single string, generating the following output:
-
- bar, baz, foo
-
-See L<Template::Manual::VMethods> for details of all the virtual
-methods available.
-
-=head1 Variable Interpolation
-
-The Template Toolkit uses C<$> consistently to indicate that a variable
-should be interpolated in position. Most frequently, you see this in
-double-quoted strings:
-
- [% fullname = "$honorific $firstname $surname" %]
-
-Or embedded in plain text when the C<INTERPOLATE> option is set:
-
- Dear $honorific $firstname $surname,
-
-The same rules apply within directives. If a variable is prefixed
-with a C<$> then it is replaced with its value before being used. The
-most common use is to retrieve an element from a hash where the key is
-stored in a variable.
-
- [% uid = 'abw' %]
- [% users.$uid %] # same as 'userlist.abw'
-
-Curly braces can be used to delimit interpolated variable names where
-necessary.
-
- [% users.${me.id}.name %]
-
-Directives such as C<INCLUDE>, C<PROCESS>, etc., that accept a template name
-as the first argument, will automatically quote it for convenience.
-
- [% INCLUDE foo/bar.txt %]
-
-The above example is equivalent to:
-
- [% INCLUDE "foo/bar.txt" %]
-
-To C<INCLUDE> a template whose name is stored in a variable, simply
-prefix the variable name with C<$> to have it interpolated.
-
- [% myfile = 'header' %]
- [% INCLUDE $myfile %]
-
-This is equivalent to:
-
- [% INCLUDE header %]
-
-Note also that a variable containing a reference to a L<Template::Document>
-object can also be processed in this way.
-
- my $vars = {
- header => Template::Document->new({ ... }),
- };
-
-Example template:
-
- [% INCLUDE $header %]
-
-=head1 Local and Global Variables
-
-Any simple variables that you create, or any changes you make to
-existing variables, will only persist while the template is being
-processed. The top-level variable hash is copied before processing
-begins and any changes to variables are made in this copy, leaving the
-original intact.
-
-The same thing happens when you C<INCLUDE> another template. The current
-namespace hash is cloned to prevent any variable changes made in the included
-template from interfering with existing variables. The C<PROCESS> option bypasses
-the localisation step altogether making it slightly faster, but requiring
-greater attention to the possibility of side effects caused by creating or
-changing any variables within the processed template.
-
- [% BLOCK change_name %]
- [% name = 'bar' %]
- [% END %]
-
- [% name = 'foo' %]
- [% INCLUDE change_name %]
- [% name %] # foo
- [% PROCESS change_name %]
- [% name %] # bar
-
-Dotted compound variables behave slightly differently because the
-localisation process is only skin deep. The current variable
-namespace hash is copied, but no attempt is made to perform a
-deep-copy of other structures within it (hashes, arrays, objects,
-etc). A variable referencing a hash, for example, will be copied to
-create a new reference but which points to the same hash. Thus, the
-general rule is that simple variables (undotted variables) are
-localised, but existing complex structures (dotted variables) are not.
-
- [% BLOCK all_change %]
- [% x = 20 %] # changes copy
- [% y.z = 'zulu' %] # changes original
- [% END %]
-
- [% x = 10
- y = { z => 'zebra' }
- %]
- [% INCLUDE all_change %]
- [% x %] # still '10'
- [% y.z %] # now 'zulu'
-
-If you create a complex structure such as a hash or list reference
-within a local template context then it will cease to exist when
-the template is finished processing.
-
- [% BLOCK new_stuff %]
- [% # define a new 'y' hash array in local context
- y = { z => 'zulu' }
- %]
- [% END %]
-
- [% x = 10 %]
- [% INCLUDE new_stuff %]
- [% x %] # outputs '10'
- [% y %] # nothing, y is undefined
-
-Similarly, if you update an element of a compound variable which
-I<doesn't> already exists then a hash will be created automatically
-and deleted again at the end of the block.
-
- [% BLOCK new_stuff %]
- [% y.z = 'zulu' %]
- [% END %]
-
-However, if the hash I<does> already exist then you will modify the
-original with permanent effect. To avoid potential confusion, it is
-recommended that you don't update elements of complex variables from
-within blocks or templates included by another.
-
-If you want to create or update truly global variables then you can
-use the 'global' namespace. This is a hash array automatically created
-in the top-level namespace which all templates, localised or otherwise
-see the same reference to. Changes made to variables within this
-hash are visible across all templates.
-
- [% global.version = 123 %]
-
-=head1 Compile Time Constant Folding
-
-In addition to variables that get resolved each time a template is
-processed, you can also define variables that get resolved just once
-when the template is compiled. This generally results in templates
-processing faster because there is less work to be done.
-
-To define compile-time constants, specify a C<CONSTANTS> hash as a
-constructor item as per C<VARIABLES>. The C<CONSTANTS> hash can contain any
-kind of complex, nested, or dynamic data structures, just like regular
-variables.
-
- my $tt = Template->new({
- CONSTANTS => {
- version => 3.14,
- release => 'skyrocket',
- col => {
- back => '#ffffff',
- fore => '#000000',
- },
- myobj => My::Object->new(),
- mysub => sub { ... },
- joint => ', ',
- },
- });
-
-Within a template, you access these variables using the C<constants>
-namespace prefix.
-
- Version [% constants.version %] ([% constants.release %])
- Background: [% constants.col.back %]
-
-When the template is compiled, these variable references are replaced
-with the corresponding value. No further variable lookup is then
-required when the template is processed.
-
-You can call subroutines, object methods, and even virtual methods on
-constant variables.
-
- [% constants.mysub(10, 20) %]
- [% constants.myobj(30, 40) %]
- [% constants.col.keys.sort.join(', ') %]
-
-One important proviso is that any arguments you pass to subroutines
-or methods must also be literal values or compile time constants.
-
-For example, these are both fine:
-
- # literal argument
- [% constants.col.keys.sort.join(', ') %]
-
- # constant argument
- [% constants.col.keys.sort.join(constants.joint) %]
-
-But this next example will raise an error at parse time because
-C<joint> is a runtime variable and cannot be determined at compile
-time.
-
- # ERROR: runtime variable argument!
- [% constants.col.keys.sort.join(joint) %]
-
-The C<CONSTANTS_NAMESPACE> option can be used to provide a different
-namespace prefix for constant variables. For example:
-
- my $tt = Template->new({
- CONSTANTS => {
- version => 3.14,
- # ...etc...
- },
- CONSTANTS_NAMESPACE => 'const',
- });
-
-Constants would then be referenced in templates as:
-
- [% const.version %]
-
-=head1 Special Variables
-
-A number of special variables are automatically defined by the Template
-Toolkit.
-
-=head2 template
-
-The C<template> variable contains a reference to the main template being
-processed, in the form of a L<Template::Document> object. This variable is
-correctly defined within C<PRE_PROCESS>, C<PROCESS> and C<POST_PROCESS>
-templates, allowing standard headers, footers, etc., to access metadata items
-from the main template. The C<name> and C<modtime> metadata items are
-automatically provided, giving the template name and modification time in
-seconds since the epoch.
-
-Note that the C<template> variable always references the top-level
-template, even when processing other template components via C<INCLUDE>,
-C<PROCESS>, etc.
-
-=head2 component
-
-The C<component> variable is like C<template> but always contains a
-reference to the current, innermost template component being processed.
-In the main template, the C<template> and C<component> variable will
-reference the same L<Template::Document> object. In any other template
-component called from the main template, the C<template> variable
-will remain unchanged, but C<component> will contain a new reference
-to the current component.
-
-This example should demonstrate the difference:
-
- $template->process('foo')
- || die $template->error(), "\n";
-
-F<foo> template:
-
- [% template.name %] # foo
- [% component.name %] # foo
- [% PROCESS footer %]
-
-F<footer> template:
-
- [% template.name %] # foo
- [% component.name %] # footer
-
-Additionally, the C<component> variable has two special fields:
-C<caller> and C<callers>. C<caller> contains the name of the template
-that called the current template (or undef if the values of C<template>
-and C<component> are the same). C<callers> contains a reference to a
-list of all the templates that have been called on the road to calling
-the current component template (like a call stack), with the
-outer-most template first.
-
-Here's an example:
-
-F<outer.tt2> template:
-
- [% component.name %] # 'outer.tt2'
- [% component.caller %] # undef
- [% component.callers %] # undef
- [% PROCESS 'middle.tt2' %]
-
-F<middle.tt2> template:
-
- [% component.name %] # 'middle.tt2'
- [% component.caller %] # 'outer.tt2'
- [% component.callers %] # [ 'outer.tt2' ]
- [% PROCESS 'inner.tt2' %]
-
-F<inner.tt2> template:
-
- [% component.name %] # 'inner.tt2'
- [% component.caller %] # 'middle.tt2'
- [% component.callers %] # [ 'outer.tt2', 'middle.tt2' ]
-
-=head2 loop
-
-Within a C<FOREACH> loop, the C<loop> variable references the
-L<Template::Iterator> object responsible for controlling the loop.
-
- [% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]
- [% "Items:\n" IF loop.first -%]
- [% loop.count %]/[% loop.size %]: [% item %]
- [% END %]
-
-=head2 error
-
-Within a C<CATCH> block, the C<error> variable contains a reference to the
-L<Template::Exception> object thrown from within the C<TRY> block. The
-C<type> and C<info> methods can be called or the variable itself can
-be printed for automatic stringification into a message of the form
-"C<$type error - $info>". See L<Template::Exception> for further details.
-
- [% TRY %]
- ...
- [% CATCH %]
- [% error %]
- [% END %]
-
-=head2 content
-
-The C<WRAPPER> method captures the output from a template block and then
-includes a named template, passing the captured output as the 'content'
-variable.
-
- [% WRAPPER box %]
- Be not afeard; the isle is full of noises,
- Sounds and sweet airs, that give delight and hurt not.
- [% END %]
-
- [% BLOCK box %]
- <blockquote class="prose">
- [% content %]
- </blockquote>
- [% END %]
-
-=head1 Compound Variables
-
-Compound 'dotted' variables may contain any number of separate
-elements. Each element may evaluate to any of the permitted variable
-types and the processor will then correctly use this value to evaluate
-the rest of the variable. Arguments may be passed to any of the
-intermediate elements.
-
- [% myorg.people.sort('surname').first.fullname %]
-
-Intermediate variables may be used and will behave entirely as expected.
-
- [% sorted = myorg.people.sort('surname') %]
- [% sorted.first.fullname %]
-
-This simplified dotted notation has the benefit of hiding the
-implementation details of your data. For example, you could implement
-a data structure as a hash array one day and then change it to an
-object the next without requiring any change to the templates.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Manual::Views
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Manual::Views - Template Toolkit views (experimental)
-
-=head1 Overview
-
-A view is effectively a collection of templates and/or variable
-definitions which can be passed around as a self-contained unit. This
-then represents a particular interface or presentation style for other
-objects or items of data.
-
-You can use views to implement custom "skins" for an application or
-content set. You can use them to help simplify the presentation of
-common objects or data types. You can even use then to automate the
-presentation of complex data structures such as that generated in an
-C<XML::DOM> tree or similar. You let an iterator do the walking, and the
-view does the talking (or in this case, the presenting). Voila - you
-have view independent, structure shy traversal using templates.
-
-In general, views can be used in a number of different ways to achieve
-several different things. They elegantly solve some problems which
-were otherwise difficult or complicated, and make easy some things
-that were previously hard.
-
-At the moment, they're still very experimental. The directive syntax
-and underlying API are likely to change quite considerably over the
-next version or two. Please be very wary about building your
-multi-million dollar e-commerce solutions based around this feature.
-
-=head1 Views as Template Collectors/Providers
-
-The C<VIEW> directive starts a view definition and includes a name by
-which the view can be referenced. The view definition continues up to
-the matching C<END> directive.
-
- [% VIEW myview %]
- ...
- [% END %]
-
-The first role of a view is to act as a collector and provider of templates.
-The C<include()> method can be called on a view to effectively do the same
-thing as the C<INCLUDE> directive. The template name is passed as the first
-argument, followed by any local variable definitions for the template.
-
- [% myview.include('header', title='The Title') %]
-
- # equivalent to
- [% INCLUDE header title='The Title' %]
-
-Views accept a number of configuration options which can be used to control
-different aspects of their behaviour. The 'C<prefix>' and 'C<suffix>' options
-can be specified to add a fixed prefix and/or suffix to the name of each template.
-
- [% VIEW myview
- prefix = 'my/'
- suffix = '.tt2' ;
- END
- %]
-
-Now the call
-
- [% myview.include('header', title='The Title') %]
-
-is equivalent to
-
- [% INCLUDE my/header.tt2 title='The Title' %]
-
-Views provide an C<AUTOLOAD> method which maps method names to the
-C<include()> method. Thus, the following are all equivalent:
-
- [% myview.include('header', title='Hello World') %]
- [% myview.include_header(title='Hello World') %]
- [% myview.header(title='Hello World') %]
-
-=head1 Local BLOCK Definitions
-
-A C<VIEW> definition can include C<BLOCK> definitions which remain local to
-the view. A request for a particular template will return a C<BLOCK>,
-if defined, in preference to any other template of the same name.
-
- [% BLOCK foo %]
- public foo block
- [% END %]
-
- [% VIEW plain %]
- [% BLOCK foo %]
- plain foo block
- [% END %]
- [% END %]
-
- [% VIEW fancy %]
- [% BLOCK foo %]
- fancy foo block
- [% END %]
- [% END %]
-
- [% INCLUDE foo %] # public foo block
- [% plain.foo %] # plain foo block
- [% fancy.foo %] # fancy foo block
-
-In addition to C<BLOCK> definitions, a C<VIEW> can contain any other
-template directives. The entire C<VIEW> definition block is processed to
-initialise the view but no output is generated (this may change RSN -
-and get stored as 'C<output>' item, subsequently accessible as C<[%
-view.output %]>). However, directives that have side-effects, such as
-those that update a variable, will have noticeable consequences.
-
-=head1 Preserving Variable State within Views
-
-Views can also be used to save the values of any existing variables,
-or to create new ones at the point at which the view is defined.
-Unlike simple template metadata (C<META>) which can only contain static
-string values, the view initialisation block can contain any template
-directives and generate any kind of dynamic output and/or data items.
-
- [% VIEW my_web_site %]
- [% view.title = title or 'My Cool Web Site' %]
- [% view.author = "$abw.name, $abw.email" %]
- [% view.sidebar = INCLUDE my/sidebar.tt2 %]
- [% END %]
-
-Note that additional data items can be specified as arguments to the C<VIEW>
-directive. Anything that doesn't look like a configuration parameter is
-assumed to be a data item. This can be a little hazardous, of course, because
-you never know when a new configuration item might get added which interferes
-with your data.
-
- [% VIEW my_web_site
- # config options
- prefix = 'my/'
- # misc data
- title = title or 'My Cool Web Site'
- author = "$abw.name, $abw.email"
- sidebar = INCLUDE my/sidebar.tt2
- %]
- ...
- [% END %]
-
-Outside of the view definition you can access the view variables as, for
-example:
-
- [% my_web_site.title %]
-
-One important feature is the equivalence of simple variables and templates.
-You can implement the view item 'C<title>' as a simple variable, a template
-defined in an external file, possibly with a prefix/suffix automatically
-appended, or as a local C<BLOCK> definition within the C<[% VIEW %] ... [% END %]>
-definition. If you use the syntax above then the view will Do The Right
-Thing to return the appropriate output.
-
-At the C<END> of the C<VIEW> definition the view is "sealed" to prevent you
-from accidentally updating any variable values. If you attempt to change
-the value of a variable after the C<END> of the C<VIEW> definition block then
-a C<view> error will be thrown.
-
- [% TRY;
- my_web_site.title = 'New Title';
- CATCH;
- error;
- END
- %]
-
-The error above will be reported as:
-
- view error - cannot update item in sealed view: title
-
-The same is true if you pass a parameter to a view variable. This is
-interpreted as an attempt to update the variable and will raise the same
-warning.
-
- [% my_web_site.title('New Title') %] # view error!
-
-You can set the C<silent> parameter to have the view ignore these
-parameters and simply return the variable value.
-
- [% VIEW my_web_site
- silent = 1
- title = title or 'My Cool Web Site'
- # ... ;
- END
- %]
-
- [% my_web_site.title('Blah Blah') %] # My Cool Web Site
-
-Alternately, you can specify that a view is unsealed allowing existing
-variables to be updated and new variables defined.
-
- [% VIEW my_web_site
- sealed = 0
- title = title or 'My Cool Web Site'
- # ... ;
- END
- %]
-
- [% my_web_site.title('Blah Blah') %] # Blah Blah
- [% my_web_site.title %] # Blah Blah
-
-=head2 Inheritance, Delegation and Reuse
-
-Views can be inherited from previously defined views by use of the C<base>
-parameter. This example shows how a base class view is defined which
-applies a C<view/default/> prefix to all template names.
-
- [% VIEW my.view.default
- prefix = 'view/default/';
- END
- %]
-
-Thus the directive:
-
- [% my.view.default.header(title='Hello World') %]
-
-is now equivalent to:
-
- [% INCLUDE view/default/header title='Hello World' %]
-
-A second view can be defined which specifies the default view as a
-base.
-
- [% VIEW my.view.fancy
- base = my.view.default
- prefix = 'view/fancy/';
- END
- %]
-
-Now the directive:
-
- [% my.view.fancy.header(title='Hello World') %]
-
-will resolve to:
-
- [% INCLUDE view/fancy/header title='Hello World' %]
-
-or if that doesn't exist, it will be handled by the base view as:
-
- [% INCLUDE view/default/header title='Hello World' %]
-
-When a parent view is specified via the C<base> parameter, the
-delegation of a view to its parent for fetching templates and accessing
-user defined variables is automatic. You can also implement your own
-inheritance, delegation or other reuse patterns by explicitly
-delegating to other views.
-
- [% BLOCK foo %]
- public foo block
- [% END %]
-
- [% VIEW plain %]
- [% BLOCK foo %]
- <plain>[% PROCESS foo %]</plain>
- [% END %]
- [% END %]
-
- [% VIEW fancy %]
- [% BLOCK foo %]
- [% plain.foo | replace('plain', 'fancy') %]
- [% END %]
- [% END %]
-
- [% plain.foo %] # <plain>public foo block</plain>
- [% fancy.foo %] # <fancy>public foo block</fancy>
-
-Note that the regular C<INCLUDE/PROCESS/WRAPPER> directives work entirely
-independently of views and will always get the original, unaltered
-template name rather than any local per-view definition.
-
-=head2 Self-Reference
-
-A reference to the view object under definition is available with the
-C<VIEW ... END> block by its specified name and also by the special name
-'C<view>' (similar to the C<my $self = shift;> in a Perl method or the
-'C<this>' pointer in C++, etc). The view is initially unsealed allowing
-any data items to be defined and updated within the C<VIEW ... END>
-block. The view is automatically sealed at the end of the definition
-block, preventing any view data from being subsequently changed.
-
-(NOTE: sealing should be optional. As well as sealing a view to prevent
-updates (C<SEALED>), it should be possible to set an option in the view to
-allow external contexts to update existing variables (C<UPDATE>) or even
-create totally new view variables (C<CREATE>)).
-
- [% VIEW fancy %]
- [% fancy.title = 'My Fancy Title' %]
- [% fancy.author = 'Frank Open' %]
- [% fancy.col = { bg => '#ffffff', bar => '#a0a0ff' } %]
- [% END %]
-
-or
-
- [% VIEW fancy %]
- [% view.title = 'My Fancy Title' %]
- [% view.author = 'Frank Open' %]
- [% view.col = { bg => '#ffffff', bar => '#a0a0ff' } %]
- [% END %]
-
-It makes no real difference in this case if you refer to the view by
-its name, 'C<fancy>', or by the general name, 'C<view>'. Outside of the
-view block, however, you should always use the given name, 'C<fancy>':
-
- [% fancy.title %]
- [% fancy.author %]
- [% fancy.col.bg %]
-
-The choice of given name or 'C<view>' is much more important when it
-comes to C<BLOCK> definitions within a C<VIEW>. It is generally recommended
-that you use 'C<view>' inside a C<VIEW> definition because this is guaranteed
-to be correctly defined at any point in the future when the block gets
-called. The original name of the view might have long since been changed
-or reused but the self-reference via 'C<view>' should always be intact and
-valid.
-
-Take the following VIEW as an example:
-
- [% VIEW foo %]
- [% view.title = 'Hello World' %]
- [% BLOCK header %]
- Title: [% view.title %]
- [% END %]
- [% END %]
-
-Even if we rename the view, or create a new C<foo> variable, the header
-block still correctly accesses the C<title> attribute of the view to
-which it belongs. Whenever a view C<BLOCK> is processed, the C<view>
-variable is always updated to contain the correct reference to the
-view object to which it belongs.
-
- [% bar = foo %]
- [% foo = { title => "New Foo" } %] # no problem
- [% bar.header %] # => Title: Hello World
-
-=head2 Saving References to External Views
-
-When it comes to view inheritance, it's always a good idea to take a
-local copy of a parent or delegate view and store it as an attribute
-within the view for later use. This ensures that the correct view
-reference is always available, even if the external name of a view
-has been changed.
-
- [% VIEW plain %]
- ...
- [% END %]
-
- [% VIEW fancy %]
- [% view.plain = plain %]
- [% BLOCK foo %]
- [% view.plain.foo | replace('plain', 'fancy') %]
- [% END %]
- [% END %]
-
- [% plain.foo %] # => <plain>public foo block</plain>
- [% plain = 'blah' %] # no problem
- [% fancy.foo %] # => <fancy>public foo block</fancy>
-
-=head2 Views as Data Presenters
-
-Another key role of a view is to act as a dispatcher to automatically
-apply the correct template to present a particular object or data
-item. This is handled via the C<print()> method.
-
-Here's an example:
-
- [% VIEW foo %]
-
- [% BLOCK text %]
- Some text: [% item %]
- [% END %]
-
- [% BLOCK hash %]
- a hash:
- [% FOREACH key = item.keys.sort -%]
- [% key %] => [% item.$key %]
- [% END -%]
- [% END %]
-
- [% BLOCK list %]
- a list: [% item.sort.join(', ') %]
- [% END %]
-
- [% END %]
-
-We can now use the view to print text, hashes or lists. The C<print()>
-method includes the right template depending on the typing of the
-argument (or arguments) passed.
-
- [% some_text = 'I read the news today, oh boy.' %]
- [% a_hash = { house => 'Lords', hall => 'Albert' } %]
- [% a_list = [ 'sure', 'Nobody', 'really' ] %]
-
- [% view.print(some_text) %]
- # Some text: I read the news today, oh boy.
-
- [% view.print(a_hash) %]
- # a hash:
- hall => Albert
- house => Lords
- [% view.print(a_list) %]
- # a list: Nobody, really, sure
-
-You can also provide templates to print objects of any other class.
-The class name is mapped to a template name with all non-word
-character sequences such as 'C<::>' converted to a single 'C<_>'.
-
- [% VIEW foo %]
- [% BLOCK Foo_Bar %]
- a Foo::Bar object:
- thingies: [% view.print(item.thingies) %]
- doodahs: [% view.print(item.doodahs) %]
- [% END %]
- [% END %]
-
- [% USE fubar = Foo::Bar(...) %]
-
- [% foo.print(fubar) %]
-
-Note how we use the view object to display various items within the
-objects ('C<thingies>' and 'C<doodahs>'). We don't need to worry what
-kind of data these represent (text, list, hash, etc) because we can
-let the view worry about it, automatically mapping the data type to
-the correct template.
-
-Views may define their own type =E<gt> template map.
-
- [% VIEW foo
- map = { TEXT => 'plain_text',
- ARRAY => 'show_list',
- HASH => 'show_hash',
- My::Module => 'template_name'
- default => 'any_old_data'
- }
- %]
- [% BLOCK plain_text %]
- ...
- [% END %]
-
- ...
- [% END %]
-
-They can also provide a C<default> map entry, specified as part of the C<map>
-hash or as a parameter by itself.
-
- [% VIEW foo
- map = { ... },
- default = 'whatever'
- %]
- ...
- [% END %]
-
-or
-
- [% VIEW foo %]
- [% view.map = { ... }
- view.default = 'whatever'
- %]
- ...
- [% END %]
-
-The C<print()> method provides one more piece of magic. If you pass it a
-reference to an object which provides a C<present()> method, then the method
-will be called passing the view as an argument. This then gives any object a
-chance to determine how it should be presented via the view.
-
- package Foo::Bar;
- ...
- sub present {
- my ($self, $view) = @_;
- return "a Foo::Bar object:\n"
- . "thingies: " . $view->print($self->{ _THINGIES }) . "\n"
- . "doodahs: " . $view->print($self->{ _DOODAHS }) . "\n";
- }
-
-The object is free to delve deeply into its innards and mess around with
-its own private data, before presenting the relevant data via the view.
-In a more complex example, a C<present()> method might walk part of a tree
-making calls back against the view to present different nodes within the
-tree. We may not want to expose the internal structure of the tree
-(because that would break encapsulation and make our presentation code
-dependant on it) but we want to have some way of walking the tree and
-presenting items found in a particular manner.
-
-This is known as I<Structure Shy Traversal>. Our view object doesn't require
-prior knowledge about the internal structure of any data set to be able
-to traverse it and present the data contained therein. The data items
-themselves, via the C<present()> method, can implement the internal iterators
-to guide the view along the right path to presentation happiness.
-
-The upshot is that you can use views to greatly simplify the display
-of data structures like C<XML::DOM> trees. The documentation for the
-C<Template::Plugin::XML::DOM> module contains an example of this. In
-essence, it looks something like this:
-
-XML source:
-
- <user name="Andy Wardley">
- <project id="iCan" title="iCan, but theyCan't"/>
- <project id="p45" title="iDid, but theyDidn't"/>
- </user>
-
-TT View:
-
- [% VIEW fancy %]
- [% BLOCK user %]
- User: [% item.name %]
- [% item.content(myview) %]
- [% END %]
-
- [% BLOCK project %]
- Project: [% project.id %] - [% project.name %]
- [% END %]
- [% END %]
-
-Generate view:
-
- [% USE dom = XML.DOM %]
- [% fancy.print(dom.parse(xml_source)) %]
-
-Output:
-
- User: Andy Wardley
- Project: iCan - iCan, but theyCan't
- Project: p45 - iDid, but theyDidn't
-
-The same approach can be applied to many other areas. Here's an example from
-the C<File>/C<Directory> plugins.
-
- [% VIEW myview %]
- [% BLOCK file %]
- - [% item.name %]
- [% END %]
-
- [% BLOCK directory %]
- * [% item.name %]
- [% item.content(myview) FILTER indent %]
- [% END %]
- [% END %]
-
- [% USE dir = Directory(dirpath) %]
- [% myview.print(dir) %]
-
-And here's the same approach use to convert POD documentation to any
-other format via template.
-
- [% # load Pod plugin and parse source file into Pod Object Model
- USE Pod;
- pom = Pod.parse_file(my_pod_file);
-
- # define view to map all Pod elements to "pod/html/xxx" templates
- VIEW pod2html
- prefix='pod/html';
- END;
-
- # now print document via view (i.e. as HTML)
- pod2html.print(pom)
- %]
-
-Here we simply define a template prefix for the view which causes the
-view to look for C<pod/html/head1>, C<pod/html/head2>, C<pod/html/over>
-as templates to present the different sections of the parsed Pod document.
-
-There are some examples in the Template Toolkit test suite: F<t/pod.t> and
-F<t/view.t> which may shed some more light on this. See the distribution
-sub-directory F<examples/pod/html> for examples of Pod -E<gt> HTML templates.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Modules
-#
-# DESCRIPTION
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Modules - Template Toolkit Modules
-
-=head1 Template Toolkit Modules
-
-This documentation provides an overview of the different modules that
-comprise the Template Toolkit.
-
-=head2 Template
-
-The L<Template> module is the front-end to the Template Toolkit for
-Perl programmers.
-
- use Template;
- my $tt = Template->new();
- $tt->process('hello.html', message => 'Hello World');
-
-=head2 Template::Base
-
-The L<Template::Base> module implements a base class from which the other
-Template Toolkit modules are derived. It implements common functionality
-for creating objects, error reporting, debugging, and so on.
-
-=head2 Template::Config
-
-The L<Template::Config> module defines the configuration of the Template
-Toolkit for your system. It is an example of a I<factory module> which is
-responsible for instantiating the various other modules used in the Template
-Toolkit.
-
-For example, the L<Template::Config> module defines the C<$STASH> package
-variable which indicates which version of the L<Template::Stash> you are
-using by default. If you elected to use the faster L<XS|Template::Stash::XS>
-stash when you installed the Template Toolkit, then this will be set as:
-
- $STASH = 'Template::Stash::XS';
-
-Otherwise you'll get the regular L<Perl|Template::Stash> stash:
-
- $STASH = 'Template::Stash';
-
-This approach means that other parts of the Template Toolkit don't have to
-worry about which stash you're using. They just ask the L<Template::Config>
-module to create a stash of the right kind.
-
-=head2 Template::Constants
-
-The L<Template::Constants> defines a number of constants that are used by
-the Template Toolkit.
-
-For example, the C<:chomp> tagset defines the C<CHOMP_???> constants that
-can be used with the C<PRE_CHOMP> and C<POST_CHOMP> configuration options.
-
- use Template::Constants ':chomp';
- my $tt = Template->new({
- PRE_CHOMP => CHOMP_COLLAPSE,
- });
-
-=head2 Template::Context
-
-The L<Template::Context> module defines a runtime context in which templates
-are processed. A context keeps track of all the templates, variables, plugins,
-and other resources that are available (either directly or through delegate
-objects) and provides methods to fetch, store, and perform various operations
-on them.
-
-=head2 Template::Document
-
-The L<Template::Document> module implements a compiled template document
-object. This is generated by the L<Template::Parser> module.
-
-=head2 Template::Exception
-
-The L<Template::Exception> module implements an exception object which
-is used for runtime error reporting.
-
-=head2 Template::Filters
-
-The L<Template::Filters> module implements a filter provider. It includes
-the core collection of filters that can be used via the C<FILTER> directive.
-
-=head2 Template::Iterator
-
-The L<Template::Iterator> module implements a data iterator which steps
-through each item in a list in turn. It is used by the C<FOREACH> directive.
-Within a C<FOREACH> block, the C<loop> variable always references the
-current iterator object.
-
- [% FOREACH item IN list;
- IF loop.first;
- # first item in loop
- ELSIF loop.last;
- # last item in loop
- ELSE;
- # any other item in loop
- END;
- END
- %]
-
-=head2 Template::Namespace::Constants
-
-The L<Template::Namespace::Constants> module is used internally to represent
-constants. These can be resolved immediately at the point that a template is
-compiled.
-
-=head2 Template::Parser
-
-The L<Template::Parser> module is used to parse a source template and turn it
-into Perl code which can be executed.
-
-=head2 Template::Plugin
-
-The L<Template::Plugin> module is a base class for Template Toolkit plugins
-that can be loaded on demand from within a template using the C<USE> directive.
-
-=head2 Template::Plugins
-
-The L<Template::Plugins> module is the plugins provider. It loads and prepares
-plugins as and when they are requested from within a template.
-
-=head2 Template::Provider
-
-The L<Template::Provider> module is responsible for loading, compiling and
-caching templates.
-
-=head2 Template::Service
-
-The L<Template::Service> module implements a service layer that sits just
-behind the L<Template> module, and just in front of a L<Template::Context>. It
-handles each request to process a template (forwarded from the L<Template>
-module). It adds any headers and/or footers (specified via the C<PRE_PROCESS>
-and C<POST_PROCESS> options), applies any wrapper (the C<WRAPPER> option) and
-catches any errors returned (the C<ERRORS> option).
-
-=head2 Template::Stash
-
-The L<Template::Stash> module is used to fetch and store template variables.
-It implements all of the magic associated with the dot operator.
-
-=head2 Template::Stash::XS
-
-The L<Template::Stash::XS> module is a high-speed implementation of
-L<Template::Stash> written in C.
-
-=head2 Template::Test
-
-The L<Template::Test> module is used to automate the Template Toolkit
-test scripts.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
--- /dev/null
+#==============================================================================
+#
+# Template::Plugin::DBI
+#
+# DESCRIPTION
+# A Template Toolkit plugin to provide access to a DBI data source.
+#
+# AUTHORS
+# Original version by Simon Matthews <sam@knowledgepool.com>
+# with some reworking by Andy Wardley <abw@kfs.org> and other
+# contributions from Craig Barratt <craig@arraycomm.com>,
+# Dave Hodgkinson <daveh@davehodgkinson.com> and Rafael Kitover
+# <caelum@debian.org>.
+# Since 2010 Jens Rehsack <sno@NetBSD.org> maintains this module.
+#
+# COPYRIGHT
+# Copyright (C) 1999-2000 Simon Matthews. All Rights Reserved.
+# Copyright (C) 2006 Andy Wardley. All Rights Reserved.
+# Copyright (C) 2010 Jens Rehsack. All Rights Reserved.
+#
+# This module is free software; you can redistribute it and/or
+# modify it under the same terms as Perl itself.
+#
+# REVISION
+# $Id$
+#
+#==============================================================================
+
+package Template::Plugin::DBI;
+
+use strict;
+use warnings;
+
+use Carp qw(croak carp);
+use DBI;
+
+use Template::Exception;
+use base 'Template::Plugin';
+
+our $VERSION = 2.65;
+our $DEBUG = 0 unless defined $DEBUG;
+our $QUERY = 'Template::Plugin::DBI::Query';
+our $ITERATOR = 'Template::Plugin::DBI::Iterator';
+
+my $threads_enabled = 0;
+my $have_tvr = 0;
+
+BEGIN
+{
+ $INC{"threads.pm"} and eval {
+ ++$threads_enabled;
+ require threads::variable::reap;
+ ++$have_tvr;
+ };
+
+ $have_tvr
+ and threads::variable::reap->import(qw(reap reapref));
+}
+
+# alias _connect() to connect() for backwards compatability
+*_connect = \*connect;
+
+#------------------------------------------------------------------------
+# new($context, @params)
+#
+# Constructor which returns a reference to a new DBI plugin object.
+# A connection string (dsn), user name and password may be passed as
+# positional arguments or a hash array of connection parameters can be
+# passed to initialise a connection. Otherwise, an unconnected DBI
+# plugin object is returned.
+#------------------------------------------------------------------------
+
+sub new
+{
+ my ( $class, $context, @connect_args ) = @_;
+ my $self =
+ ref $class
+ ? $class
+ : bless {
+ _CONTEXT => $context,
+ _STH => undef,
+ }, $class;
+
+ $self->connect(@connect_args) if @connect_args;
+
+ return $self;
+}
+
+#------------------------------------------------------------------------
+# connect( $data_source, $username, $password, $attributes )
+# connect( { data_source => 'dbi:driver:database'
+# username => 'foo'
+# password => 'bar' } )
+#
+# Opens a DBI connection for the plugin.
+#------------------------------------------------------------------------
+
+sub connect
+{
+ my $self = shift;
+ my $params = ref $_[-1] eq 'HASH' ? pop(@_) : {};
+ my ( $dbh, $dsn, $user, $pass, $klobs );
+
+ # set debug flag
+ exists $params->{debug} and $DEBUG = $params->{debug};
+ $self->{_DEBUG} = $params->{debug} || 0;
+
+ # fetch 'dbh' named paramater or use positional arguments or named
+ # parameters to specify 'dsn', 'user' and 'pass'
+
+ if ( $dbh = $params->{dbh} )
+ {
+ # disconnect any existing database handle that we previously opened
+ $self->{_DBH}->disconnect()
+ if $self->{_DBH} && $self->{_DBH_CONNECT};
+
+ # store new dbh but leave _DBH_CONNECT false to prevent us
+ # from automatically closing it in the future
+ $self->{_DBH} = $dbh;
+ $self->{_DBH_CONNECT} = 0;
+ }
+ else
+ {
+ # certain Perl programmers are known to have problems with short
+ # term memory loss (see Tie::Hash::Cannabinol) so we let the poor
+ # blighters fumble any kind of argument that looks like it might
+ # identify the database
+
+ $dsn =
+ shift
+ || delete $params->{data_source}
+ || delete $params->{database}
+ || delete $params->{connect}
+ || delete $params->{dsn}
+ || delete $params->{db}
+ || delete $self->{_DSN}
+ || $ENV{DBI_DSN}
+ || return $self->_throw('data source not defined');
+
+ # add 'dbi:' prefix if it's not there
+ $dsn = "dbi:$dsn" unless $dsn =~ /^dbi:/i;
+
+ $user =
+ shift
+ || delete $params->{username}
+ || delete $params->{user}
+ || delete $self->{_USER};
+
+ $pass =
+ shift
+ || delete $params->{password}
+ || delete $params->{pass}
+ || delete $self->{_PASS};
+
+ $user ||= '';
+ $pass ||= '';
+
+ # save connection data because we might need it later to do a tie()
+ @$self{qw( _DSN _USER _PASS )} = ( $dsn, $user, $pass );
+
+ # reuse existing database handle if connection params match
+ my $connect = join( ':', $dsn, $user, $pass );
+ return ''
+ if $self->connected() && $self->{_DBH_CONNECT} eq $connect;
+
+ # otherwise disconnect any existing database handle that we opened
+ $self->disconnect();
+
+ # don't need DBI to automatically print errors because all calls go
+ # via this plugin interface and we always check return values
+ $params->{PrintError} = 0
+ unless defined $params->{PrintError};
+ $params->{RaiseError} = 0
+ unless defined $params->{RaiseError};
+
+ $self->{_DBH} = DBI->connect_cached( $dsn, $user, $pass, $params )
+ || return $self->_throw("DBI connect failed: $DBI::errstr");
+
+ # store the connection parameters
+ $self->{_DBH_CONNECT} = $connect;
+ }
+
+ $have_tvr
+ and reap( $self->{_DBH} )
+ and reap( $self->{_STH} );
+
+ return '';
+}
+
+sub connected
+{
+ my $self = $_[0];
+ return $self->{_DBH} && $self->{_DBH}->isa('DBI::db');
+}
+
+#------------------------------------------------------------------------
+# disconnect()
+#
+# Disconnects the current active database connection.
+#------------------------------------------------------------------------
+
+sub disconnect
+{
+ my $self = $_[0];
+ delete( $self->{_STH} ); # first DESTROY any queries
+ $self->connected() and $self->{_DBH}->disconnect();
+ delete $self->{_DBH};
+ delete $self->{_DSN};
+ delete $self->{_USER};
+ delete $self->{_PASS};
+ delete $self->{_DBH_CONNECT};
+ return '';
+}
+
+#------------------------------------------------------------------------
+# tie( $table, $key )
+#
+# Return a hash tied to a table in the database, indexed by the specified
+# key.
+#------------------------------------------------------------------------
+
+sub tie
+{
+ my $self = shift;
+ my $params = ref $_[-1] eq 'HASH' ? pop(@_) : {};
+ my ( $table, $key, $klobs, $debug, %hash );
+
+ eval { require Tie::DBI };
+ $self->_throw("failed to load Tie::DBI module: $@") if $@;
+
+ $table =
+ shift
+ || $params->{table}
+ || $self->_throw('table not defined');
+
+ $key =
+ shift
+ || $params->{key}
+ || $self->_throw('key not defined');
+
+ # Achtung der Klobberman!
+ $klobs = $params->{clobber};
+ $klobs = $params->{CLOBBER} unless defined $klobs;
+
+ # going the extra mile to allow user to use UPPER or lower case or
+ # inherit internel debug flag set by connect()
+ $debug = $params->{debug};
+ $debug = $params->{DEBUG} unless defined $debug;
+ $debug = $self->{_DEBUG} unless defined $debug;
+
+ tie %hash, 'Tie::DBI', {
+ %$params, # any other Tie::DBI options like DEBUG, WARN, etc
+ db => $self->{_DBH} || $self->{_DSN},
+ user => $self->{_USER},
+ password => $self->{_PASS},
+ table => $table,
+ key => $key,
+ CLOBBER => $klobs || 0,
+ DEBUG => $debug || 0,
+ };
+
+ return \%hash;
+}
+
+#------------------------------------------------------------------------
+# prepare($sql)
+#
+# Prepare a query and store the live statement handle internally for
+# subsequent execute() calls.
+#------------------------------------------------------------------------
+
+sub prepare
+{
+ my ($self,@args) = @_;
+ unless( @args and $args[0] and "" eq ref($args[0]) )
+ {
+ return $self->_throw("prepare called without statement");
+ }
+
+ my $sth = $self->dbh()->prepare(@args)
+ || return $self->_throw( "DBI prepare failed: " . $self->dbh()->errstr );
+
+ # create wrapper object around handle to return to template client
+ $sth = $QUERY->new($sth);
+ $self->{_STH} = $sth;
+
+ return $sth;
+}
+
+#------------------------------------------------------------------------
+# execute()
+#
+# Calls execute() on the most recent statement created via prepare().
+#------------------------------------------------------------------------
+
+sub execute
+{
+ my $self = shift;
+ my @args = @_ == 1 && ref $_[0] eq 'ARRAY' ? @{ $_[0] } : @_;
+
+ my $sth = $self->{_STH}
+ || return $self->_throw('no query prepared');
+
+ $sth->execute(@args);
+}
+
+#------------------------------------------------------------------------
+# query($sql, @params)
+#
+# Prepares and executes a SQL query.
+#------------------------------------------------------------------------
+
+sub query
+{
+ my ( $self, $sql, @args ) = @_;
+ my @prep = ($sql);
+
+ if( @args and $args[0] and ref($args[0]) eq 'HASH' )
+ {
+ push(@prep, shift @args);
+ }
+
+ return $self->prepare(@prep)->execute(@args);
+}
+
+#------------------------------------------------------------------------
+# do($sql, \%attr, @bind)
+#
+# Prepares and executes a SQL statement.
+#------------------------------------------------------------------------
+
+sub do
+{
+ my $self = shift;
+ my @args = @_ == 1 && ref $_[0] eq 'ARRAY' ? @{ $_[0] } : @_;
+
+ return $self->dbh()->do(@args)
+ || $self->_throw( "DBI do failed: " . $self->dbh()->errstr );
+}
+
+#------------------------------------------------------------------------
+# quote($value [, $data_type ])
+#
+# Returns a quoted string (correct for the connected database) from the
+# value passed in.
+#------------------------------------------------------------------------
+
+sub quote
+{
+ my ( $self, @quote_args ) = @_;
+ return $self->dbh()->quote(@quote_args);
+}
+
+#------------------------------------------------------------------------
+# dbh()
+#
+# Internal method to retrieve the database handle belonging to the
+# instance or attempt to create a new one using connect.
+#------------------------------------------------------------------------
+
+sub dbh
+{
+ my $self = $_[0];
+
+ $self->{_DBH} or $self->connect;
+
+ return $self->{_DBH};
+}
+
+#------------------------------------------------------------------------
+# DESTROY
+#
+# Called automatically when the plugin object goes out of scope to
+# disconnect the database handle cleanly
+#------------------------------------------------------------------------
+
+sub DESTROY
+{
+ my $self = $_[0];
+ delete( $self->{_STH} ); # first DESTROY any queries
+ $self->{_DBH}->disconnect()
+ if ( $self->connected() && $self->{_DBH_CONNECT} );
+}
+
+#------------------------------------------------------------------------
+# _throw($error)
+#
+# Raise an error by throwing it via die() as a Template::Exception
+# object of type 'DBI'.
+#------------------------------------------------------------------------
+
+sub _throw
+{
+ my $self = shift;
+ my $error = shift || croak "DBI throw() called without an error string";
+
+ # throw error as DBI exception
+ die( Template::Exception->new( 'DBI', $error ) );
+}
+
+sub fetch
+{
+ my ( $self, $attr ) = @_;
+
+ return $self->_throw("Cannot fetch attribute on not connected \$dbh") unless ( $self->connected() );
+
+ my $dbh = $_[0]->{_DBH};
+ local $@ = undef;
+ my $value;
+ eval { $value = $dbh->{$attr}; };
+ return $self->_throw($@) if ($@);
+
+ return $value;
+}
+
+sub store
+{
+ my ( $self, $attr, $value ) = @_;
+
+ return $self->_throw("Cannot store attribute on not connected \$dbh") unless ( $self->connected() );
+
+ my $dbh = $_[0]->{_DBH};
+ local $@ = undef;
+ eval { $dbh->{$attr} = $value; };
+ return $self->_throw($@) if ($@);
+
+ return 1;
+}
+
+#========================================================================
+# Template::Plugin::DBI::Query
+#========================================================================
+
+package Template::Plugin::DBI::Query;
+use vars qw( $DEBUG $ITERATOR $AUTOLOAD );
+
+use Scalar::Util qw(blessed);
+
+*DEBUG = \$Template::Plugin::DBI::DEBUG;
+*ITERATOR = \$Template::Plugin::DBI::ITERATOR;
+
+sub new
+{
+ my ( $class, $sth ) = @_;
+ my $self = bless( { _STH => $sth }, $class );
+}
+
+sub execute
+{
+ my $self = shift;
+ my @args = @_ == 1 && ref $_[0] eq 'ARRAY' ? @{ $_[0] } : @_;
+
+ $self->{_STH}->execute(@args)
+ || return Template::Plugin::DBI->_throw( "execute failed: " . $self->{_STH}->errstr );
+
+ $ITERATOR->new($self);
+}
+
+sub DESTROY
+{
+ undef $_[0]->{_STH};
+}
+
+sub AUTOLOAD
+{
+ my ( $self, @args ) = @_;
+
+ die Template::Exception->new( 'DBI', "$self is not an object" ) unless ( blessed($self) );
+ die Template::Exception->new( 'DBI', "No statement handle" ) unless ( defined( $self->{_STH} ) );
+
+ ( my $name = $AUTOLOAD ) =~ s/.*://;
+ return $self->{_STH}->$name(@args);
+}
+
+#========================================================================
+# Template::Plugin::DBI::Iterator;
+#========================================================================
+
+package Template::Plugin::DBI::Iterator;
+
+use Template::Iterator;
+use base qw( Template::Iterator );
+use vars qw( $DEBUG );
+
+*DEBUG = \$Template::Plugin::DBI::DEBUG;
+
+sub new
+{
+ my ( $class, $sth, $params ) = @_;
+
+ my $rows = $sth->rows();
+
+ my $self = bless {
+ _STH => $sth,
+ SIZE => $rows,
+ MAX => $rows - 1,
+ }, $class;
+
+ return $self;
+}
+
+#------------------------------------------------------------------------
+# get_first()
+#
+# Initialises iterator to read from statement handle. We maintain a
+# one-record lookahead buffer to allow us to detect if the current
+# record is the last in the series.
+#------------------------------------------------------------------------
+
+sub get_first
+{
+ my $self = shift;
+ $self->{_STARTED} = 1;
+
+ # set some status variables into $self
+ @$self{qw( PREV ITEM FIRST LAST COUNT INDEX )} = ( undef, undef, 2, 0, 0, -1 );
+
+ # support 'number' as an alias for 'count' for backwards compatability
+ $self->{NUMBER} = 0;
+
+ print STDERR "get_first() called\n" if $DEBUG;
+
+ # get the first row
+ $self->_fetchrow();
+
+ print STDERR "get_first() calling get_next()\n" if $DEBUG;
+
+ return $self->get_next();
+}
+
+#------------------------------------------------------------------------
+# get_next()
+#
+# Called to read remaining result records from statement handle.
+#------------------------------------------------------------------------
+
+sub get_next
+{
+ my $self = shift;
+ my ( $data, $fixup );
+
+ # increment the 'index' and 'count' counts
+ $self->{INDEX}++;
+ $self->{COUNT}++;
+ $self->{NUMBER}++; # 'number' is old name for 'count'
+
+ # decrement the 'first-record' flag
+ $self->{FIRST}-- if $self->{FIRST};
+
+ # we should have a row already cache in NEXT
+ return ( undef, Template::Constants::STATUS_DONE )
+ unless $data = $self->{NEXT};
+
+ # set PREV to be current ITEM from last iteration
+ $self->{PREV} = $self->{ITEM};
+
+ # look ahead to the next row so that the rowcache is refilled
+ $self->_fetchrow();
+
+ $self->{ITEM} = $data;
+ return ( $data, Template::Constants::STATUS_OK );
+}
+
+sub get
+{
+ my $self = shift;
+ my ( $data, $error );
+
+ ( $data, $error ) = $self->{_STARTED} ? $self->get_next() : $self->get_first();
+
+ return $data;
+}
+
+sub get_all
+{
+ my $self = shift;
+ my $sth = $self->{_STH};
+
+ my $data = $sth->fetchall_arrayref( {} );
+ $self->throw( $sth->errstr ) if ( $sth->err() );
+ unshift( @$data, $self->{NEXT} ) if $self->{NEXT};
+ $self->{LAST} = 1;
+ $self->{NEXT} = undef;
+
+ return $data;
+}
+
+sub get_colnames
+{
+ my $self = shift;
+ my $sth = $self->{_STH};
+ my $error;
+
+ my $data = $sth->{_STH}->{NAME_lc};
+ $self->throw( $sth->errstr ) if ( $sth->err() );
+
+ return $data;
+}
+
+sub get_COLnames
+{
+ my $self = shift;
+ my $sth = $self->{_STH};
+
+ my $data = $sth->{_STH}->{NAME_uc};
+ $self->throw( $sth->errstr ) if ( $sth->err() );
+
+ return $data;
+}
+
+sub get_all_list
+{
+ my $self = shift;
+ my $sth = $self->{_STH};
+
+ my $data = $sth->fetchall_arrayref();
+ $self->throw( $sth->errstr ) if ( $sth->err() );
+ if ( $self->{NEXT} )
+ {
+ my $fetch_hash_key_name = $self->{_STH}->{FetchHashKeyName};
+ my @cols = @{ $self->{_STH}->{$fetch_hash_key_name} };
+ my @row = @{ $self->{NEXT} }[@cols];
+ unshift( @$data, \@row );
+ }
+ $self->{LAST} = 1;
+ $self->{NEXT} = undef;
+
+ return $data;
+}
+
+sub rows
+{
+ return $_[0]->{SIZE};
+}
+
+sub fetch
+{
+ my ( $self, $attr ) = @_;
+ $self->{_STH}->FETCH($attr);
+}
+
+sub store
+{
+ my ( $self, $attr, $value ) = @_;
+ return $self->{_STH}->STORE( $attr, $value );
+}
+
+#------------------------------------------------------------------------
+# _fetchrow()
+#
+# Retrieve a record from the statement handle and store in row cache.
+#------------------------------------------------------------------------
+
+sub _fetchrow
+{
+ my $self = shift;
+ my $sth = $self->{_STH};
+
+ my $data = $sth->fetchrow_hashref() || do
+ {
+ $self->{LAST} = 1;
+ $self->{NEXT} = undef;
+ return;
+ };
+ $self->{NEXT} = $data;
+ return;
+}
+
+1;
+
+__END__
+
+=head1 NAME
+
+Template::Plugin::DBI - Template interface to the DBI module
+
+=head1 SYNOPSIS
+
+Making an implicit database connection:
+
+ # ...using positional arguments
+ [% USE DBI('dbi:driver:dbname', 'user', 'pass') %]
+
+ # ...using named parameters
+ [% USE DBI( database = 'dbi:driver:dbname',
+ username = 'user',
+ password = 'pass' )
+ %]
+
+ # ...using short named parameters (4 lzy ppl and bad typsits)
+ [% USE DBI( db = 'driver:dbname',
+ user = 'user',
+ pass = 'pass' )
+ %]
+
+ # ...or an existing DBI database handle
+ [% USE DBI( dbh = my_dbh_ref ) %]
+
+Making explicit database connections:
+
+ [% USE DBI %]
+
+ [% DBI.connect(db, user, pass) %]
+ ...
+
+ [% DBI.connect(new_db, new_user, new_pass) %]
+ ...
+
+ [% DBI.disconnect %] # final disconnect is optional
+
+Making an automagical database connection using DBI_DSN environment variable:
+
+ [% USE DBI %]
+
+Making database queries:
+
+ # single step query
+ [% FOREACH user = DBI.query('SELECT * FROM users') %]
+ [% user.uid %] blah blah [% user.name %] etc. etc.
+ [% END %]
+
+ # two stage prepare/execute
+ [% query = DBI.prepare('SELECT * FROM users WHERE uid = ?') %]
+
+ [% FOREACH user = query.execute('sam') %]
+ ...
+ [% END %]
+
+ [% FOREACH user = query.execute('abw') %]
+ ...
+ [% END %]
+
+Making non-SELECT statements:
+
+ [% IF DBI.do("DELETE FROM users WHERE uid = '$uid'") %]
+ The user '[% uid %]' was successfully deleted.
+ [% END %]
+
+Using named DBI connections:
+
+ [% USE one = DBI(...) %]
+ [% USE two = DBI(...) %]
+
+ [% FOREACH item = one.query("SELECT ...etc...") %]
+ ...
+ [% END %]
+
+ [% FOREACH item = two.query("SELECT ...etc...") %]
+ ...
+ [% END %]
+
+Tieing to a database table (via Tie::DBI):
+
+ [% people = DBI.tie('users', 'uid') %]
+
+ [% me = people.abw %] # => SELECT * FROM users WHERE uid='abw'
+
+ I am [% me.name %]
+
+ # clobber option allows table updates (see Tie::DBI)
+ [% people = DBI.tie('users', 'uid', clobber=1) %]
+
+ [% people.abw.name = 'not a number' %]
+
+ I am [% people.abw.name %] # I am a free man!
+
+=head1 DESCRIPTION
+
+This Template Toolkit plugin module provides an interface to the Perl
+DBI/DBD modules, allowing you to integrate SQL queries into your
+template documents. It also provides an interface via the Tie::DBI
+module (if installed on your system) so that you can access database
+records without having to embed any SQL in your templates.
+
+A DBI plugin object can be created as follows:
+
+ [% USE DBI %]
+
+This creates an uninitialised DBI object. You can then open a connection
+to a database using the connect() method.
+
+ [% DBI.connect('dbi:driver:dbname', 'user', 'pass') %]
+
+The DBI connection can be opened when the plugin is created by passing
+arguments to the constructor, called from the USE directive.
+
+ [% USE DBI('dbi:driver:dbname', 'user', 'pass') %]
+
+You can also use named parameters to provide the data source connection
+string, user name and password.
+
+ [% USE DBI(database => 'dbi:driver:dbname',
+ username => 'user',
+ password => 'pass') %]
+
+For backwards compatability with previous versions of this plugin, you can
+also spell 'database' as 'data_source'.
+
+ [% USE DBI(data_source => 'dbi:driver:dbname',
+ username => 'user',
+ password => 'pass') %]
+
+Lazy Template hackers may prefer to use 'db', 'dsn' or 'connect' as a
+shorthand form of the 'database' parameter, and 'user' and 'pass' as
+shorthand forms of 'username' and 'password', respectively. You can
+also drop the 'dbi:' prefix from the database connect string because
+the plugin will add it on for you automagically.
+
+ [% USE DBI(db => 'driver:dbname',
+ user => 'user',
+ pass => 'pass') %]
+
+Any additional DBI attributes can be specified as named parameters.
+The 'PrintError' attribute defaults to 0 unless explicitly set true.
+
+ [% USE DBI(db, user, pass, ChopBlanks=1) %]
+
+An alternate variable name can be provided for the plugin as per regular
+Template Toolkit syntax:
+
+ [% USE mydb = DBI('dbi:driver:dbname', 'user', 'pass') %]
+
+ [% FOREACH item = mydb.query('SELECT * FROM users') %]
+ ...
+ [% END %]
+
+You can also specify the DBI plugin name in lower case if you prefer:
+
+ [% USE dbi(dsn, user, pass) %]
+
+ [% FOREACH item = dbi.query('SELECT * FROM users') %]
+ ...
+ [% END %]
+
+The disconnect() method can be called to explicitly disconnect the
+current database, but this generally shouldn't be necessary as it is
+called automatically when the plugin goes out of scope. You can call
+connect() at any time to open a connection to another database. The
+previous connection will be closed automatically.
+
+Internally, the DBI connect_cached() method is used instead of the
+connect() method. This allows for connection caching in a server
+environment, such as when the Template Toolkit is used from an Apache
+mod_perl handler. In such a case, simply enable the mod_env module
+and put in a line such as:
+
+ SetEnv DBI_DSN "dbi:mysql:dbname;host=dbhost;
+ user=uname;password=pword"
+
+(NOTE: the string shown here is split across 2 lines for the sake of
+reasonable page formatting, but you should specify it all as one long
+string with no spaces or newlines).
+
+You can then use the DBI plugin without any parameters or the need
+to explicitly call connect().
+
+Once you've loaded a DBI plugin and opened a database connection using
+one of the techniques shown above, you can then make queries on the database
+using the familiar dotted notation:
+
+ [% FOREACH user = DBI.query('SELECT * FROM users') %]
+ [% user.uid %] blah blah [% user.name %] etc. etc.
+ [% END %]
+
+The query() method prepares a query and executes it all in one go.
+If you want to repeat a query with different parameters then you
+can use a separate prepare/execute cycle.
+
+ [% query = DBI.prepare('SELECT * FROM users WHERE uid = ?') %]
+
+ [% FOREACH user = query.execute('sam') %]
+ ...
+ [% END %]
+
+ [% FOREACH user = query.execute('abw') %]
+ ...
+ [% END %]
+
+The query() and execute() methods return an iterator object which
+manages the result set returned. You can save a reference to the
+iterator and access methods like size() to determine the number of
+rows returned by a query.
+
+ [% users = DBI.query('SELECT * FROM users') %]
+ [% users.size %] records returned
+
+or even
+
+ [% DBI.query('SELECT * FROM users').size %]
+
+When used within a FOREACH loop, the iterator is always aliased to the
+special C<loop> variable. This makes it possible to do things like this:
+
+ [% FOREACH user = DBI.query('SELECT * FROM users') %]
+ [% loop.count %]/[% loop.size %]: [% user.name %]
+ [% END %]
+
+to generate a result set of the form:
+
+ 1/3: Jerry Garcia
+ 2/3: Kurt Cobain
+ 3/3: Freddie Mercury
+
+See L<Template::Iterator> for further details on iterators and the
+methods that they implement.
+
+The DBI plugin also provides the do() method to execute non-SELECT
+statements like this:
+
+ [% IF DBI.do("DELETE FROM users WHERE uid = '$uid'") %]
+ The user '[% uid %]' was successfully deleted.
+ [% END %]
+
+The plugin also allows you to create a tie to a table in the database
+using the Tie::DBI module. Simply call the tie() method, passing the
+name of the table and the primary key as arguments.
+
+ [% people = DBI.tie('person', 'uid') %]
+
+You can then access records in the database table as if they were
+entries in the 'people' hash.
+
+ My name is [% people.abw.name %]
+
+IMPORTANT NOTE: the XS Stash (Template::Stash::XS) does not currently
+support access to tied hashes. If you are using the XS stash and having
+problems then you should try enabling the regular stash instead. You
+can do this by setting $Template::Config::STASH to 'Template::Stash'
+before instantiating the Template object.
+
+=head1 OBJECT METHODS
+
+=head2 connect($database, $username, $password)
+
+Establishes a database connection. This method accepts both positional
+and named parameter syntax. e.g.
+
+ [% DBI.connect( 'dbi:driver:dbname', 'timmy', 'sk8D00Dz' ) %]
+
+ [% DBI.connect( database = 'dbi:driver:dbname'
+ username = 'timmy'
+ password = 'sk8D00Dz' ) %]
+
+The connect method allows you to connect to a data source explicitly.
+It can also be used to reconnect an exisiting object to a different
+data source.
+
+If you already have a database handle then you can instruct the plugin
+to reuse it by passing it as the 'dbh' parameter.
+
+ [% DBI.connect( dbh = my_dbh_ref ) %]
+
+=head2 query($sql,[\%args],[@bind_values])
+
+This method submits an SQL query to the database and creates an iterator
+object to return the results. This may be used directly in a FOREACH
+directive as shown below. Data is automatically fetched a row at a time
+from the query result set as required for memory efficiency.
+
+ [% FOREACH user = DBI.query('SELECT * FROM users') %]
+ Each [% user.field %] can be printed here
+ [% END %]
+
+=head2 prepare($sql,[\%args])
+
+Prepare a query for later execution. This returns a compiled query
+object (of the Template::Plugin::DBI::Query class) on which the
+execute() method can subsequently be called.
+
+ [% query = DBI.prepare('SELECT * FROM users WHERE id = ?') %]
+
+=head2 execute(@bind_values)
+
+Execute a previously prepared query. This method should be called on
+the query object returned by the prepare() method. Returns an
+iterator object which can be used directly in a FOREACH directive.
+
+ [% query = DBI.prepare('SELECT * FROM users WHERE manager = ?') %]
+
+ [% FOREACH minion = query.execute('abw') %]
+ [% minion.name %]
+ [% END %]
+
+ [% FOREACH minion = query.execute('sam') %]
+ [% minion.name %]
+ [% END %]
+
+=head2 do($sql,[\%attr,[@bind_values]])
+
+The do() method executes a sql statement from which no records are
+returned. It will return true if the statement was successful
+
+ [% IF DBI.do("DELETE FROM users WHERE uid = 'sam'") %]
+ The user was successfully deleted.
+ [% END %]
+
+=head2 tie($table, $key, \%args)
+
+Returns a reference to a hash array tied to a table in the database,
+implemented using the Tie::DBI module. You should pass the name of
+the table and the key field as arguments.
+
+ [% people = DBI.tie('users', 'uid') %]
+
+Or if you prefer, you can use the 'table' and 'key' named parameters.
+
+ [% people = DBI.tie(table='users', key='uid') %]
+
+In this example, the Tie::DBI module will convert the accesses into
+the 'people' hash into SQL queries of the form:
+
+ SELECT * FROM users WHERE uid=?
+
+For example:
+
+ [% me = people.abw %]
+
+The record returned can then be accessed just like a normal hash.
+
+ I am [% me.name %]
+
+You can also do things like this to iterate through all the records
+in a table.
+
+ [% FOREACH uid = people.keys.sort;
+ person = people.$uid
+ %]
+ * [% person.id %] : [% person.name %]
+ [% END %]
+
+With the 'clobber' (or 'CLOBBER') option set you can update the record
+and have those changes automatically permeated back into the database.
+
+ [% people = DBI.tie('users', 'uid', clobber=1) %]
+
+ [% people.abw.name = 'not a number' %]
+
+ I am [% people.abw.name %] # I am a free man!
+
+And you can also add new records.
+
+ [% people.newguy = {
+ name = 'Nobby Newguy'
+ ...other fields...
+ }
+ %]
+
+See L<Tie::DBI> for further information on the 'CLOBBER' option.
+
+=head2 quote($value, $type)
+
+Calls the quote() method on the underlying DBI handle to quote the value
+specified in the appropriate manner for its type.
+
+=head2 dbh
+
+ [% DBI.dbh() %]
+
+Return the database handle currently in use by the plugin.
+
+=head2 disconnect
+
+ [% DBI.disconnect() %]
+
+Disconnects the current database.
+
+=head2 fetch
+
+ [% DBI.fetch('Name') %]
+
+Fetches an attribute from the connected database handle.
+Throws an exception when not connected.
+
+=head2 store
+
+ [% DBI.store('RowCacheSize',0) %]
+
+Stores an attribute in the connected database handle.
+Throws an exception when not connected.
+
+=head1 ITERATOR METHODS
+
+=head2 get_all
+
+ [% allhash = result.get_all() %]
+
+Returns all (remaining) rows as a hash.
+
+=head2 get_all_list
+
+ [% allhash = result.get_all_list() %]
+
+Returns all (remaining) rows as a list.
+
+=head2 rows
+
+Returns the number of affected rows of the executed statement.
+
+=head2 get_colnames
+
+Returns the lowercase column names (C<$sth> attribute C<< ->{NAME_lc} >>).
+
+=head2 get_COLnames
+
+Returns the uppercase column names (C<$sth> attribute C<< ->{NAME_uc} >>).
+
+=head2 fetch
+
+Fetches an attribute from the statement handle.
+
+ [% result.fetch('FetchHashKeyName') %]
+
+=head2 store
+
+Stores an attribute to the statement handle.
+
+ [% result.store('FetchHashKeyName','NAME_lc') %]
+
+=head1 AUTHORS
+
+The DBI plugin was originally written by Simon A Matthews, and
+distributed as a separate module. It was integrated into the Template
+Toolkit distribution for version 2.00 and includes contributions from
+Andy Wardley, Craig Barratt, Dave Hodgkinson and Rafael Kitover. Andy
+Wardley extracted it back into a separate distribution in May 2006.
+After that, in 2010 Jens Rehsack maintains this distribution.
+
+=head1 COPYRIGHT
+
+ Copyright (C) 1999-2006 Simon Matthews, Andy Wardley. All Rights Reserved.
+ Copyright (C) 2010 Jens Rehsack. All Rights Reserved
+
+This module is free software; you can redistribute it and/or
+modify it under the same terms as Perl itself.
+
+=head1 SEE ALSO
+
+L<Template> L<Template::Plugins>, L<DBI>, L<Tie::DBI>
+
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Tools
-#
-# DESCRIPTION
-# Index page for documentation about the command line tools
-# distributed with the Template Toolkit.
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Tools - Command Line Tools for the Template Toolkit
-
-=head1 Template Tools
-
-The Template Toolkit includes the following command line tools
-for processing templates.
-
-=head2 tpage
-
-The L<tpage|Template::Tools::tpage> script can be used to process
-a single template using the Template Toolkit.
-
- $ tpage --define msg="Hello World" greeting.tt2
-
-Use the C<-h> option to get a summary of options:
-
- $ tpage -h
-
-See the L<Template::Tools::tpage> documentation for further information
-and examples of use.
-
-=head2 ttree
-
-The L<ttree|Template::Tools::ttree> script can be used to process
-an entire directory of templates.
-
- $ ttree --src /path/to/templates --dest /path/to/output
-
-Use the C<-h> option to get a summary of options:
-
- $ ttree -h
-
-See the L<Template::Tools::ttree> documentation for further information
-and examples of use.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-=head1 NAME
-
-Template::Tools::tpage - Process templates from command line
-
-=head1 USAGE
-
- tpage [ --define var=value ] file(s)
-
-=head1 DESCRIPTION
-
-The B<tpage> script is a simple wrapper around the Template Toolkit processor.
-Files specified by name on the command line are processed in turn by the
-template processor and the resulting output is sent to STDOUT and can be
-redirected accordingly. e.g.
-
- tpage myfile > myfile.out
- tpage header myfile footer > myfile.html
-
-If no file names are specified on the command line then B<tpage> will read
-STDIN for input.
-
-The C<--define> option can be used to set the values of template variables.
-e.g.
-
- tpage --define author="Andy Wardley" skeleton.pm > MyModule.pm
-
-=head2 The F<.tpagerc> Configuration File
-
-You can use a F<.tpagerc> file in your home directory.
-
-The purpose of this file is to set any I<global> configuration options
-that you want applied I<every> time F<tpage> is run. For example, you
-can use the C<include_path> to use template files from a generic template
-directory.
-
-Run C<tpage -h> for a summary of the options available.
-
-See L<Template> for general information about the Perl Template
-Toolkit and the template language and features.
-
-=head1 AUTHOR
-
-Andy Wardley L<http://wardley.org/>
-
-=head1 COPYRIGHT
-
-Copyright (C) 1996-2008 Andy Wardley. All Rights Reserved.
-
-This module is free software; you can redistribute it and/or
-modify it under the same terms as Perl itself.
-
-=head1 SEE ALSO
-
-L<ttree|Template::Tools::ttree>
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-=head1 NAME
-
-Template::Tools::ttree - Process entire directory trees of templates
-
-=head1 SYNOPSIS
-
- ttree [options] [files]
-
-=head1 DESCRIPTION
-
-The F<ttree> script is used to process entire directory trees containing
-template files. The resulting output from processing each file is then
-written to a corresponding file in a destination directory. The script
-compares the modification times of source and destination files (where
-they already exist) and processes only those files that have been modified.
-In other words, it is the equivalent of 'make' for the Template Toolkit.
-
-It supports a number of options which can be used to configure
-behaviour, define locations and set Template Toolkit options. The
-script first reads the F<.ttreerc> configuration file in the HOME
-directory, or an alternative file specified in the TTREERC environment
-variable. Then, it processes any command line arguments, including
-any additional configuration files specified via the C<-f> (file)
-option.
-
-=head2 The F<.ttreerc> Configuration File
-
-When you run F<ttree> for the first time it will ask you if you want
-it to create a F<.ttreerc> file for you. This will be created in your
-home directory.
-
- $ ttree
- Do you want me to create a sample '.ttreerc' file for you?
- (file: /home/abw/.ttreerc) [y/n]: y
- /home/abw/.ttreerc created. Please edit accordingly and re-run ttree
-
-The purpose of this file is to set any I<global> configuration options
-that you want applied I<every> time F<ttree> is run. For example, you
-can use the C<ignore> and C<copy> option to provide regular expressions
-that specify which files should be ignored and which should be copied
-rather than being processed as templates. You may also want to set
-flags like C<verbose> and C<recurse> according to your preference.
-
-A minimal F<.ttreerc>:
-
- # ignore these files
- ignore = \b(CVS|RCS)\b
- ignore = ^#
- ignore = ~$
-
- # copy these files
- copy = \.(gif|png|jpg|pdf)$
-
- # recurse into directories
- recurse
-
- # provide info about what's going on
- verbose
-
-In most cases, you'll want to create a different F<ttree> configuration
-file for each project you're working on. The C<cfg> option allows you
-to specify a directory where F<ttree> can find further configuration
-files.
-
- cfg = /home/abw/.ttree
-
-The C<-f> command line option can be used to specify which configuration
-file should be used. You can specify a filename using an absolute or
-relative path:
-
- $ ttree -f /home/abw/web/example/etc/ttree.cfg
- $ ttree -f ./etc/ttree.cfg
- $ ttree -f ../etc/ttree.cfg
-
-If the configuration file does not begin with C</> or C<.> or something
-that looks like a MS-DOS absolute path (e.g. C<C:\\etc\\ttree.cfg>) then
-F<ttree> will look for it in the directory specified by the C<cfg> option.
-
- $ ttree -f test1 # /home/abw/.ttree/test1
-
-The C<cfg> option can only be used in the F<.ttreerc> file. All the
-other options can be used in the F<.ttreerc> or any other F<ttree>
-configuration file. They can all also be specified as command line
-options.
-
-Remember that F<.ttreerc> is always processed I<before> any
-configuration file specified with the C<-f> option. Certain options
-like C<lib> can be used any number of times and accumulate their values.
-
-For example, consider the following configuration files:
-
-F</home/abw/.ttreerc>:
-
- cfg = /home/abw/.ttree
- lib = /usr/local/tt2/templates
-
-F</home/abw/.ttree/myconfig>:
-
- lib = /home/abw/web/example/templates/lib
-
-When F<ttree> is invoked as follows:
-
- $ ttree -f myconfig
-
-the C<lib> option will be set to the following directories:
-
- /usr/local/tt2/templates
- /home/abw/web/example/templates/lib
-
-Any templates located under F</usr/local/tt2/templates> will be used
-in preference to those located under
-F</home/abw/web/example/templates/lib>. This may be what you want,
-but then again, it might not. For this reason, it is good practice to
-keep the F<.ttreerc> as simple as possible and use different
-configuration files for each F<ttree> project.
-
-=head2 Directory Options
-
-The C<src> option is used to define the directory containing the
-source templates to be processed. It can be provided as a command
-line option or in a configuration file as shown here:
-
- src = /home/abw/web/example/templates/src
-
-Each template in this directory typically corresponds to a single
-web page or other document.
-
-The C<dest> option is used to specify the destination directory for the
-generated output.
-
- dest = /home/abw/web/example/html
-
-The C<lib> option is used to define one or more directories containing
-additional library templates. These templates are not documents in
-their own right and typically comprise of smaller, modular components
-like headers, footers and menus that are incorporated into pages templates.
-
- lib = /home/abw/web/example/templates/lib
- lib = /usr/local/tt2/templates
-
-The C<lib> option can be used repeatedly to add further directories to
-the search path.
-
-A list of templates can be passed to F<ttree> as command line arguments.
-
- $ ttree foo.html bar.html
-
-It looks for these templates in the C<src> directory and processes them
-through the Template Toolkit, using any additional template components
-from the C<lib> directories. The generated output is then written to
-the corresponding file in the C<dest> directory.
-
-If F<ttree> is invoked without explicitly specifying any templates
-to be processed then it will process every file in the C<src> directory.
-If the C<-r> (recurse) option is set then it will additionally iterate
-down through sub-directories and process and other template files it finds
-therein.
-
- $ ttree -r
-
-If a template has been processed previously, F<ttree> will compare the
-modification times of the source and destination files. If the source
-template (or one it is dependant on) has not been modified more
-recently than the generated output file then F<ttree> will not process
-it. The F<-a> (all) option can be used to force F<ttree> to process
-all files regardless of modification time.
-
- $ ttree -a
-
-Any templates explicitly named as command line argument are always
-processed and the modification time checking is bypassed.
-
-=head2 File Options
-
-The C<ignore>, C<copy> and C<accept> options are used to specify Perl
-regexen to filter file names. Files that match any of the C<ignore>
-options will not be processed. Remaining files that match any of the
-C<copy> regexen will be copied to the destination directory. Remaining
-files that then match any of the C<accept> criteria are then processed
-via the Template Toolkit. If no C<accept> parameter is specified then
-all files will be accepted for processing if not already copied or
-ignored.
-
- # ignore these files
- ignore = \b(CVS|RCS)\b
- ignore = ^#
- ignore = ~$
-
- # copy these files
- copy = \.(gif|png|jpg|pdf)$
-
- # accept only .tt2 templates
- accept = \.tt2$
-
-The C<suffix> option is used to define mappings between the file
-extensions for source templates and the generated output files. The
-following example specifies that source templates with a C<.tt2>
-suffix should be output as C<.html> files:
-
- suffix tt2=html
-
-Or on the command line,
-
- --suffix tt2=html
-
-You can provide any number of different suffix mappings by repeating
-this option.
-
-=head2 Template Dependencies
-
-The C<depend> and C<depend_file> options allow you to specify
-how any given template file depends on another file or group of files.
-The C<depend> option is used to express a single dependency.
-
- $ ttree --depend foo=bar,baz
-
-This command line example shows the C<--depend> option being used to
-specify that the F<foo> file is dependant on the F<bar> and F<baz>
-templates. This option can be used many time on the command line:
-
- $ ttree --depend foo=bar,baz --depend crash=bang,wallop
-
-or in a configuration file:
-
- depend foo=bar,baz
- depend crash=bang,wallop
-
-The file appearing on the left of the C<=> is specified relative to
-the C<src> or C<lib> directories. The file(s) appearing on the right
-can be specified relative to any of these directories or as absolute
-file paths.
-
-For example:
-
- $ ttree --depend foo=bar,/tmp/baz
-
-To define a dependency that applies to all files, use C<*> on the
-left of the C<=>.
-
- $ ttree --depend *=header,footer
-
-or in a configuration file:
-
- depend *=header,footer
-
-Any templates that are defined in the C<pre_process>, C<post_process>,
-C<process> or C<wrapper> options will automatically be added to the
-list of global dependencies that apply to all templates.
-
-The C<depend_file> option can be used to specify a file that contains
-dependency information.
-
- $ ttree --depend_file=/home/abw/web/example/etc/ttree.dep
-
-Here is an example of a dependency file:
-
- # This is a comment. It is ignored.
-
- index.html: header footer menubar
-
- header: titlebar hotlinks
-
- menubar: menuitem
-
- # spanning multiple lines with the backslash
- another.html: header footer menubar \
- sidebar searchform
-
-Lines beginning with the C<#> character are comments and are ignored.
-Blank lines are also ignored. All other lines should provide a
-filename followed by a colon and then a list of dependant files
-separated by whitespace, commas or both. Whitespace around the colon
-is also optional. Lines ending in the C<\> character are continued
-onto the following line.
-
-Files that contain spaces can be quoted. That is only necessary
-for files after the colon (':'). The file before the colon may be
-quoted if it contains a colon.
-
-As with the command line options, the C<*> character can be used
-as a wildcard to specify a dependency for all templates.
-
- * : config,header
-
-=head2 Template Toolkit Options
-
-F<ttree> also provides access to the usual range of Template Toolkit
-options. For example, the C<--pre_chomp> and C<--post_chomp> F<ttree>
-options correspond to the C<PRE_CHOMP> and C<POST_CHOMP> options.
-
-Run C<ttree -h> for a summary of the options available.
-
-=head1 AUTHORS
-
-Andy Wardley E<lt>abw@wardley.orgE<gt>
-
-L<http://www.wardley.org>
-
-With contributions from Dylan William Hardison (support for
-dependencies), Bryce Harrington (C<absolute> and C<relative> options),
-Mark Anderson (C<suffix> and C<debug> options), Harald Joerg and Leon
-Brocard who gets everywhere, it seems.
-
-=head1 COPYRIGHT
-
-Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-
-This module is free software; you can redistribute it and/or
-modify it under the same terms as Perl itself.
-
-=head1 SEE ALSO
-
-L<Template::Tools::tpage|tpage>
-
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Tutorial
-#
-# DESCRIPTION
-# Section index for the Template::Tutorial documentation.
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Tutorial - Template Toolkit Tutorials
-
-=head1 Template Toolkit Tutorials
-
-=head2 Template::Tutorial::Web
-
-The L<Template::Tutorial::Web> tutorial shows how you can use the
-Template Toolkit to generate static and dynamic web content.
-
-=head2 Template::Tutorial::Datafile
-
-The L<Template::Tutorial::Datafile> tutorial shows how you can
-use the Template Toolkit to generate other data formats like XML.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Tutorial::Datafile
-#
-# DESCRIPTION
-
-#
-# AUTHOR
-# Dave Cross <dave@dave.org.uk>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2008 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Tutorial::Datafile - Creating Data Output Files Using the Template Toolkit
-
-=head1 DESCRIPTION
-
-
-
-=head1 Introducing the Template Toolkit
-
-There are a number of Perl modules that are universally
-recognised as The Right Thing To Use for certain tasks. If you
-accessed a database without using DBI, pulled data from the WWW
-without using one of the LWP modules or parsed XML without using
-XML::Parser or one of its subclasses then you'd run the risk of
-being shunned by polite Perl society.
-
-I believe that the year 2000 saw the emergence of another 'must
-have' Perl module - the Template Toolkit. I don't think I'm
-alone in this belief as the Template Toolkit won the 'Best New
-Module' award at the Perl Conference last summer. Version 2.0 of
-the Template Toolkit (known as TT2 to its friends) was recently
-released to the CPAN.
-
-TT2 was designed and written by Andy Wardley E<lt>abw@wardley.orgE<gt>.
-It was born out of Andy's previous templating module,
-Text::Metatext, in best Fred Brooks 'plan to throw one away'
-manner; and aims to be the most useful (or, at least, the most
-I<used>) Perl templating system.
-
-TT2 provides a way to take a file of fixed boilerplate text
-(the template) and embed variable data within it. One obvious
-use of this is in the creation of dynamic web pages and this is
-where a lot of the attention that TT2 has received has been
-focussed. In this article, I hope to demonstrate that TT2 is
-just as useful in non-web applications.
-
-=head1 Using the Template Toolkit
-
-Let's look at how we'd use TT2 to process a simple data file.
-TT2 is an object oriented Perl module. Having downloaded it from
-CPAN and installed it in the usual manner, using it in your
-program is as easy as putting the lines
-
- use Template;
- my $tt = Template->new;
-
-in your code. The constructor function, C<new>, takes
-a number of optional parameters which are documented in the
-copious manual pages that come with the module, but for the
-purposes of this article we'll keep things as simple as
-possible.
-
-To process the template, you would call the C<process> method
-like this
-
- $tt->process('my_template', \%data)
- || die $tt->error;
-
-We pass two parameters to C<process>, the first is the name of
-the file containing the template to process (in this case,
-my_template) and the second is a reference to a hash which
-contains the data items that you want to use in the template. If
-processing the template gives any kind of error, the program
-will die with a (hopefully) useful error message.
-
-So what kinds of things can go in C<%data>? The answer is just
-about anything. Here's an example showing data about English
-Premier League football teams.
-
- my @teams = ({ name => 'Man Utd',
- played => 16,
- won => 12,
- drawn => 3,
- lost => 1 },
- { name => 'Bradford',
- played => 16,
- won => 2,
- drawn => 5,
- lost => 9 });
-
- my %data = ( name => 'English Premier League',
- season => '2000/01',
- teams => \@teams );
-
-This creates three data items which can be accessed within the
-template, called C<name>, C<season> and C<teams>. Notice that
-C<teams> is a complex data structure.
-
-Here is a template that we might use to process this data.
-
- League Standings
-
- League Name: [% name %]
- Season : [% season %]
-
- Teams:
- [% FOREACH team = teams -%]
- [% team.name %] [% team.played -%]
- [% team.won %] [% team.drawn %] [% team.lost %]
- [% END %]
-
-Running this template with this data gives us the following
-output
-
- League Standings
-
- League Name: English Premier League
- Season : 2000/01
-
- Teams:
- Man Utd 16 12 3 1
- Bradford 16 2 5 9
-
-Hopefully the syntax of the template is simple enough to
-follow. There are a few points to note.
-
-=over 4
-
-=item *
-
-Template processing directives are written using a simple
-language which is not Perl.
-
-=item *
-
-The keys of the C<%data> have become the names of the data
-variables within the template.
-
-=item *
-
-Template processing directives are surrounded by C<[%> and
-C<%]> sequences.
-
-=item *
-
-If these tags are replaced with C<[%-> C<-%]> then the preceding
-or following linefeed is suppressed.
-
-=item *
-
-In the C<FOREACH> loop, each element of the C<teams> list was
-assigned, in turn, to the temporary variable C<team>.
-
-=item *
-
-Each item assigned to the C<team> variable is a Perl hash.
-Individual values within the hash are accessed using a dot notation.
-
-=back
-
-It's probably the first and last of these points which are the
-most important. The first point emphasises the separation of the
-data acquisition logic from the presentation logic. The person
-creating the presentation template doesn't need to know Perl,
-they only need to know the data items which will be passed into
-the template.
-
-The last point demonstrates the way that TT2 protects the
-template designer from the implementation of the data structures.
-The data objects passed to the template processor can be scalars,
-arrays, hashes, objects or even subroutines. The template
-processor will just interpret your data correctly and Do The
-Right Thing to return the correct value to you. In this example
-each team was a hash, but in a larger system each team might be
-an object, in which case C<name>, C<played>, etc. would be accessor
-methods to the underlying object attributes. No changes would be
-required to the template as the template processor would realise
-that it needed to call methods rather than access hash values.
-
-=head2 A more complex example
-
-Stats about the English Football League are usually presented in
-a slightly more complex format than the one we used above. A
-full set of stats will show the number of games that a team has
-won, lost or drawn, the number of goals scored for and against
-the team and the number of points that the team therefore has.
-Teams gain three points for a win and one point for a draw. When
-teams have the same number of points they are separated by the
-goal difference, that is the number of goals the team has scored
-minus the number of team scored against them. To complicate
-things even further, the games won, drawn and lost and the goals
-for and against are often split between home and away games.
-
-Therefore if you have a data source which lists the team name
-together with the games won, drawn and lost and the goals for and
-against split into home and away (a total of eleven data items)
-you can calculate all of the other items (goal difference,
-points awarded and even position in the league). Let's take such
-a file, but we'll only look at the top three teams. It will look
-something like this:
-
- Man Utd,7,1,0,26,4,5,2,1,15,6
- Arsenal,7,1,0,17,4,2,3,3,7,9
- Leicester,4,3,1,10,8,4,2,2,7,4
-
-A simple script to read this data into an array of hashes will
-look something like this (I've simplified the names of the data
-columns - w, d, and l are games won, drawn and lost and f and a
-are goals scored for and against; h and a at the front of a data
-item name indicates whether it's a home or away statistic):
-
- my @cols = qw(name hw hd hl hf ha aw ad al af aa);
-
- my @teams;
- while (<>) {
- chomp;
-
- my %team;
-
- @team{@cols} = split /,/;
-
- push @teams, \%team;
- }
-
-We can then go thru the teams again and calculate all of the
-derived data items:
-
- foreach (@teams) {
- $_->{w} = $_->{hw} + $_->{aw};
- $_->{d} = $_->{hd} + $_->{ad};
- $_->{l} = $_->{hl} + $_->{al};
-
- $_->{pl} = $_->{w} + $_->{d} + $_->{l};
-
- $_->{f} = $_->{hf} + $_->{af};
- $_->{a} = $_->{ha} + $_->{aa};
-
- $_->{gd} = $_->{f} - $_->{a};
- $_->{pt} = (3 * $_->{w}) + $_->{d};
- }
-
-And then produce a list sorted in descending order:
-
- @teams = sort {
- $b->{pt} <=> $b->{pt} || $b->{gd} <=> $a->{gd}
- } @teams;
-
-And finally add the league position data item:
-
- $teams[$_]->{pos} = $_ + 1
- foreach 0 .. $#teams;
-
-Having pulled all of our data into an internal data structure
-we can start to produce output using out templates. A template
-to create a CSV file containing the data split between home and
-away stats would look like this:
-
- [% FOREACH team = teams -%]
- [% team.pos %],[% team.name %],[% team.pl %],[% team.hw %],
- [%- team.hd %],[% team.hl %],[% team.hf %],[% team.ha %],
- [%- team.aw %],[% team.ad %],[% team.al %],[% team.af %],
- [%- team.aa %],[% team.gd %],[% team.pt %]
- [%- END %]
-
-And processing it like this:
-
- $tt->process('split.tt', { teams => \@teams }, 'split.csv')
- || die $tt->error;
-
-produces the following output:
-
- 1,Man Utd,16,7,1,0,26,4,5,2,1,15,6,31,39
- 2,Arsenal,16,7,1,0,17,4,2,3,3,7,9,11,31
- 3,Leicester,16,4,3,1,10,8,4,2,2,7,4,5,29
-
-Notice that we've introduced the third parameter to C<process>.
-If this parameter is missing then the TT2 sends its output to
-C<STDOUT>. If this parameter is a scalar then it is taken as the
-name of a file to write the output to. This parameter can also be
-(amongst other things) a filehandle or a reference to an object
-which is assumed to implement a C<print> method.
-
-If we weren't interested in the split between home and away games,
-then we could use a simpler template like this:
-
- [% FOREACH team = teams -%]
- [% team.pos %],[% team.name %],[% team.pl %],[% team.w %],
- [%- team.d %],[% team.l %],[% team.f %],[% team.a %],
- [%- team.aa %],[% team.gd %],[% team.pt %]
- [% END -%]
-
-Which would produce output like this:
-
- 1,Man Utd,16,12,3,1,41,10,6,31,39
- 2,Arsenal,16,9,4,3,24,13,9,11,31
- 3,Leicester,16,8,5,3,17,12,4,5,29
-
-=head1 Producing XML
-
-This is starting to show some of the power and flexibility of
-TT2, but you may be thinking that you could just as easily produce
-this output with a C<foreach> loop and a couple of C<print>
-statements in your code. This is, of course, true; but that's
-because I've chosen a deliberately simple example to explain the
-concepts. What if we wanted to produce an XML file containing the
-data? And what if (as I mentioned earlier) the league data was held
-in an object? The code would then look even easier as most of the code
-we've written earlier would be hidden away in C<FootballLeague.pm>.
-
- use FootballLeague;
- use Template;
-
- my $league = FootballLeague->new(name => 'English Premier');
-
- my $tt = Template->new;
-
- $tt->process('league_xml.tt', { league => $league })
- || die $tt->error;
-
-And the template in C<league_xml.tt> would look something like this:
-
- <?xml version="1.0"?>
- <!DOCTYPE LEAGUE SYSTEM "league.dtd">
-
- <league name="[% league.name %]" season="[% league.season %]">
- [% FOREACH team = league.teams -%]
- <team name="[% team.name %]"
- pos="[% team.pos %]"
- played="[% team.pl %]"
- goal_diff="[% team.gd %]"
- points="[% team.pt %]">
- <stats type="home">
- win="[% team.hw %]"
- draw="[%- team.hd %]"
- lose="[% team.hl %]"
- for="[% team.hf %]"
- against="[% team.ha %]" />
- <stats type="away">
- win="[% team.aw %]"
- draw="[%- team.ad %]"
- lose="[% team.al %]"
- for="[% team.af %]"
- against="[% team.aa %]" />
- </team>
- [% END -%]
- &/league>
-
-Notice that as we've passed the whole object into C<process> then
-we need to put an extra level of indirection on our template
-variables - everything is now a component of the C<league> variable.
-Other than that, everything in the template is very similar to what
-we've used before. Presumably now C<team.name> calls an accessor
-function rather than carrying out a hash lookup, but all of this
-is transparent to our template designer.
-
-=head1 Multiple Formats
-
-As a final example, let's suppose that we need to create output
-football league tables in a number of formats. Perhaps we are
-passing this data on to other people and they can't all use the
-same format. Some of our users need CSV files and others need
-XML. Some require data split between home and away matches and
-other just want the totals. In total, then, we'll need four
-different templates, but the good news is that they can use the
-same data object. All the script needs to do is to establish
-which template is required and process it.
-
- use FootballLeague;
- use Template;
-
- my ($name, $type, $stats) = @_;
-
- my $league = FootballLeague->new(name => $name);
-
- my $tt = Template->new;
-
- $tt->process("league_${type}_$stats.tt",
- { league => $league }
- "league_$stats.$type")
- || die $tt->error;
-
-For example, you can call this script as
-
- league.pl 'English Premier' xml split
-
-This will process a template called C<league_xml_split.tt>
-and put the results in a file called C<league_split.xml>.
-
-This starts to show the true strength of the Template Toolkit.
-If we later wanted to add another file format - perhaps we
-wanted to create a league table HTML page or even a LaTeX
-document - then we would just need to create the appropriate
-template and name it according to our existing naming
-convention. We would need to make no changes to the code.
-
-I hope you can now see why the Template Toolkit is fast becoming
-an essential part of many people's Perl installation.
-
-=head1 AUTHOR
-
-Dave Cross E<lt>dave@dave.org.ukE<gt>
-
-
-
-
-=head1 VERSION
-
-Template Toolkit version 2.19, released on 27 April 2007.
-
-=head1 COPYRIGHT
-
-
-Copyright (C) 2001 Dave Cross E<lt>dave@dave.org.ukE<gt>
-
-This module is free software; you can redistribute it and/or
-modify it under the same terms as Perl itself.
-
-
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
+++ /dev/null
-#============================================================= -*-perl-*-
-#
-# Template::Tutorial::Web
-#
-# DESCRIPTION
-# Tutorial on generating web content with the Template Toolkit
-#
-# AUTHOR
-# Andy Wardley <abw@wardley.org>
-#
-# COPYRIGHT
-# Copyright (C) 1996-2008 Andy Wardley. All Rights Reserved.
-#
-# This module is free software; you can redistribute it and/or
-# modify it under the same terms as Perl itself.
-#
-#========================================================================
-
-=head1 NAME
-
-Template::Tutorial::Web - Generating Web Content Using the Template Toolkit
-
-=head1 Overview
-
-This tutorial document provides a introduction to the Template Toolkit and
-demonstrates some of the typical ways it may be used for generating web
-content. It covers the generation of static pages from templates using the
-L<tpage|Template::Tools::tpage> and L<ttree|Template::Tools::ttree> scripts
-and then goes on to show dynamic content generation using CGI scripts and
-Apache/mod_perl handlers.
-
-Various features of the Template Toolkit are introduced and described briefly
-and explained by use of example. For further information, see L<Template>,
-L<Template::Manual> and the various sections within it. e.g
-
- perldoc Template # Template.pm module usage
- perldoc Template::Manual # index to manual
- perldoc Template::Manual::Config # e.g. configuration options
-
-The documentation is also available in HTML format to read online, or download
-from the Template Toolkit web site:
-
- http://template-toolkit.org/docs/
-
-=head1 Introduction
-
-The Template Toolkit is a set of Perl modules which collectively
-implement a template processing system.
-
-A template is a text document with special markup tags embedded in it.
-By default, the Template Toolkit uses 'C<[%>' and 'C<%]>' to denote
-the start and end of a tag. Here's an example:
-
- [% INCLUDE header %]
-
- People of [% planet %], your attention please.
-
- This is [% captain %] of the
- Galactic Hyperspace Planning Council.
-
- As you will no doubt be aware, the plans
- for development of the outlying regions
- of the Galaxy require the building of a
- hyperspatial express route through your
- star system, and regrettably your planet
- is one of those scheduled for destruction.
-
- The process will take slightly less than
- [% time %].
-
- Thank you.
-
- [% INCLUDE footer %]
-
-Tags can contain simple I<variables> (like C<planet> and C<captain>) and more
-complex I<directives> that start with an upper case keyword (like C<INCLUDE>).
-A directive is an instruction that tells the template processor to perform
-some action, like processing another template (C<header> and C<footer> in this
-example) and inserting the output into the current template. In fact, the
-simple variables we mentioned are actually C<GET> directives, but the C<GET>
-keyword is optional.
-
- People of [% planet %], your attention please. # short form
- People of [% GET planet %], your attention please. # long form
-
-Other directives include C<SET> to set a variable value (the C<SET> keyword is
-also optional), C<FOREACH> to iterate through a list of values, and C<IF>,
-C<UNLESS>, C<ELSIF> and C<ELSE> to declare conditional blocks.
-
-The Template Toolkit processes all I<text> files equally, regardless of what
-kind of content they contain. So you can use TT to generate HTML, XML, CSS,
-Javascript, Perl, RTF, LaTeX, or any other text-based format. In this tutorial,
-however, we'll be concentrating on generating HTML for web pages.
-
-=head1 Generating Static Web Content
-
-Here's an example of a template used to generate an HTML document.
-
- [% INCLUDE header
- title = 'This is an HTML example';
-
- pages = [
- { url = 'http://foo.org'
- title = 'The Foo Organisation'
- }
- { url = 'http://bar.org'
- title = 'The Bar Organisation'
- }
- ]
- %]
- <h1>Some Interesting Links</h1>
- <ul>
- [% FOREACH page IN pages %]
- <li><a href="[% page.url %]">[% page.title %]</a>
- [% END %]
- </ul>
-
- [% INCLUDE footer %]
-
-This example shows how the C<INCLUDE> directive is used to load and process
-separate 'C<header>' and 'C<footer>' template files, including the output in
-the current document. These files might look something like this:
-
-header:
-
- <html>
- <head>
- <title>[% title %]</title>
- </head>
- <body>
-
-footer:
-
- <div class="copyright">
- © Copyright 2007 Arthur Dent
- </div>
- </body>
- </html>
-
-The example also uses the C<FOREACH> directive to iterate through the
-'C<pages>' list to build a table of links. In this example, we have defined
-this list within the template to contain a number of hash references, each
-containing a 'C<url>' and 'C<title>' member. The C<FOREACH> directive iterates
-through the list, aliasing 'C<page>' to each item (in this case, hash array
-references). The C<[% page.url %]> and C<[% page.title %]> directives then
-access the individual values in the hash arrays and insert them into the
-document.
-
-=head2 Using tpage
-
-Having created a template file we can now process it to generate some real
-output. The quickest and easiest way to do this is to use the
-L<tpage|Template::Tools::tpage> script. This is provided as part of the
-Template Toolkit and should be installed in your usual Perl bin directory.
-
-Assuming you saved your template file as F<example.html>, you would run
-the command:
-
- $ tpage example.html
-
-This will process the template file, sending the output to C<STDOUT> (i.e.
-whizzing past you on the screen). You may want to redirect the output to a
-file but be careful not to specify the same name as the template file, or
-you'll overwrite it. You may want to use one prefix for your templates (e.g.
-'C<.tt>') and another (e.g. 'C<.html>') for the output files.
-
- $ tpage example.tt > example.html
-
-Or you can redirect the output to another directory. e.g.
-
- $ tpage templates/example.tt > html/example.html
-
-The output generated would look like this:
-
- <html>
- <head>
- <title>This is an HTML example</title>
- </head>
- <body>
- <h1>Some Interesting Links</h1>
- <ul>
- <li><a href="http://foo.org">The Foo Organsiation</a>
- <li><a href="http://bar.org">The Bar Organsiation</a>
- </ul>
- <div class="copyright">
- © Copyright 2007 Arthur Dent
- </div>
- </body>
- </html>
-
-The F<header> and F<footer> template files have been included (assuming
-you created them and they're in the current directory) and the link data
-has been built into an HTML list.
-
-=head2 Using ttree
-
-The L<tpage|Template::Tools::tpage> script gives you a simple and easy way to
-process a single template without having to write any Perl code. The
-L<ttree:Template::Tools::ttree> script, also distributed as part of the
-Template Toolkit, provides a more flexible way to process a number of template
-documents in one go.
-
-The first time you run the script, it will ask you if it should create a
-configuration file (F<.ttreerc>) in your home directory. Answer C<y> to have
-it create the file.
-
-The L<ttree:Template::Tools::ttree> documentation describes how you can change
-the location of this file and also explains the syntax and meaning of the
-various options in the file. Comments are written to the sample configuration
-file which should also help.
-
-In brief, the configuration file describes the directories in which template
-files are to be found (C<src>), where the corresponding output should be
-written to (C<dest>), and any other directories (C<lib>) that may contain
-template files that you plan to C<INCLUDE> into your source documents. You can
-also specify processing options (such as C<verbose> and C<recurse>) and provide
-regular expression to match files that you don't want to process (C<ignore>,
-C<accept>)> or should be copied instead of being processed as templates (C<copy>).
-
-An example F<.ttreerc> file is shown here:
-
-$HOME/.ttreerc:
-
- verbose
- recurse
-
- # this is where I keep other ttree config files
- cfg = ~/.ttree
-
- src = ~/websrc/src
- lib = ~/websrc/lib
- dest = ~/public_html/test
-
- ignore = \b(CVS|RCS)\b
- ignore = ^#
-
-You can create many different configuration files and store them
-in the directory specified in the C<cfg> option, shown above. You then
-add the C<-f filename> option to C<ttree> to have it read that file.
-
-When you run the script, it compares all the files in the C<src> directory
-(including those in sub-directories if the C<recurse> option is set), with
-those in the C<dest> directory. If the destination file doesn't exist or
-has an earlier modification time than the corresponding source file, then
-the source will be processed with the output written to the destination
-file. The C<-a> option forces all files to be processed, regardless of
-modification times.
-
-The script I<doesn't> process any of the files in the C<lib> directory, but it
-does add it to the C<INCLUDE_PATH> for the template processor so that it can
-locate these files via an C<INCLUDE>, C<PROCESS> or C<WRAPPER> directive.
-Thus, the C<lib> directory is an excellent place to keep template elements
-such as header, footers, etc., that aren't complete documents in their own
-right.
-
-You can also specify various Template Toolkit options from the configuration
-file. Consult the L<ttree|Template::Tools::ttree> documentation and help
-summary (C<ttree -h>) for full details. e.g.
-
-$HOME/.ttreerc:
-
- pre_process = config
- interpolate
- post_chomp
-
-The C<pre_process> option allows you to specify a template file which
-should be processed before each file. Unsurprisingly, there's also a
-C<post_process> option to add a template after each file. In the
-fragment above, we have specified that the C<config> template should be
-used as a prefix template. We can create this file in the C<lib>
-directory and use it to define some common variables, including those
-web page links we defined earlier and might want to re-use in other
-templates. We could also include an HTML header, title, or menu bar
-in this file which would then be prepended to each and every template
-file, but for now we'll keep all that in a separate C<header> file.
-
-$lib/config:
-
- [% root = '~/abw'
- home = "$root/index.html"
- images = "$root/images"
- email = 'abw@wardley.org'
- graphics = 1
- webpages = [
- { url => 'http://foo.org', title => 'The Foo Organsiation' }
- { url => 'http://bar.org', title => 'The Bar Organsiation' }
- ]
- %]
-
-Assuming you've created or copied the C<header> and C<footer> files from the
-earlier example into your C<lib> directory, you can now start to create
-web pages like the following in your C<src> directory and process them
-with C<ttree>.
-
-$src/newpage.html:
-
- [% INCLUDE header
- title = 'Another Template Toolkit Test Page'
- %]
-
- <a href="[% home %]">Home</a>
- <a href="mailto:[% email %]">Email</a>
-
- [% IF graphics %]
- <img src="[% images %]/logo.gif" align=right width=60 height=40>
- [% END %]
-
- [% INCLUDE footer %]
-
-Here we've shown how pre-defined variables can be used as flags to
-enable certain feature (e.g. C<graphics>) and to specify common items
-such as an email address and URL's for the home page, images directory
-and so on. This approach allows you to define these values once so
-that they're consistent across all pages and can easily be changed to
-new values.
-
-When you run F<ttree>, you should see output similar to the following
-(assuming you have the verbose flag set).
-
- ttree 2.9 (Template Toolkit version 2.20)
-
- Source: /home/abw/websrc/src
- Destination: /home/abw/public_html/test
- Include Path: [ /home/abw/websrc/lib ]
- Ignore: [ \b(CVS|RCS)\b, ^# ]
- Copy: [ ]
- Accept: [ * ]
-
- + newpage.html
-
-The C<+> in front of the C<newpage.html> filename shows that the file was
-processed, with the output being written to the destination directory. If you
-run the same command again, you'll see the following line displayed instead
-showing a C<-> and giving a reason why the file wasn't processed.
-
- - newpage.html (not modified)
-
-It has detected a C<newpage.html> in the destination directory which is
-more recent than that in the source directory and so hasn't bothered
-to waste time re-processing it. To force all files to be processed,
-use the C<-a> option. You can also specify one or more filenames as
-command line arguments to C<ttree>:
-
- tpage newpage.html
-
-This is what the destination page looks like.
-
-$dest/newpage.html:
-
- <html>
- <head>
- <title>Another Template Toolkit Test Page</title>
- </head>
- <body>
-
- <a href="~/abw/index.html">Home</a>
- <a href="mailto:abw@wardley.org">Email me</a>
- <img src="~/abw/images/logo.gif" align=right width=60 height=40>
-
- <div class="copyright">
- © Copyright 2007 Arthur Dent
- </div>
- </body>
- </html>
-
-You can add as many documents as you like to the C<src> directory and
-C<ttree> will apply the same process to them all. In this way, it is
-possible to build an entire tree of static content for a web site with
-a single command. The added benefit is that you can be assured of
-consistency in links, header style, or whatever else you choose to
-implement in terms of common templates elements or variables.
-
-=head1 Dynamic Content Generation Via CGI Script
-
-The L<Template> module provides a simple front-end to the Template Toolkit for
-use in CGI scripts and Apache/mod_perl handlers. Simply C<use> the L<Template>
-module, create an object instance with the L<new()> method and then call the
-L<process()> method on the object, passing the name of the template file as a
-parameter. The second parameter passed is a reference to a hash array of
-variables that we want made available to the template:
-
- #!/usr/bin/perl
- use strict;
- use warnings;
- use Template;
-
- my $file = 'src/greeting.html';
- my $vars = {
- message => "Hello World\n"
- };
-
- my $template = Template->new();
-
- $template->process($file, $vars)
- || die "Template process failed: ", $template->error(), "\n";
-
-So that our scripts will work with the same template files as our earlier
-examples, we'll can add some configuration options to the constructor to
-tell it about our environment:
-
- my $template->new({
- # where to find template files
- INCLUDE_PATH => ['/home/abw/websrc/src', '/home/abw/websrc/lib'],
- # pre-process lib/config to define any extra values
- PRE_PROCESS => 'config',
- });
-
-Note that here we specify the C<config> file as a C<PRE_PROCESS> option.
-This means that the templates we process can use the same global
-variables defined earlier for our static pages. We don't have to
-replicate their definitions in this script. However, we can supply
-additional data and functionality specific to this script via the hash
-of variables that we pass to the C<process()> method.
-
-These entries in this hash may contain simple text or other values,
-references to lists, others hashes, sub-routines or objects. The Template
-Toolkit will automatically apply the correct procedure to access these
-different types when you use the variables in a template.
-
-Here's a more detailed example to look over. Amongst the different
-template variables we define in C<$vars>, we create a reference to a
-L<CGI> object and a C<get_user_projects()> sub-routine.
-
- #!/usr/bin/perl
- use strict;
- use warnings;
- use Template;
- use CGI;
-
- $| = 1;
- print "Content-type: text/html\n\n";
-
- my $file = 'userinfo.html';
- my $vars = {
- 'version' => 3.14,
- 'days' => [ qw( mon tue wed thu fri sat sun ) ],
- 'worklist' => \&get_user_projects,
- 'cgi' => CGI->new(),
- 'me' => {
- 'id' => 'abw',
- 'name' => 'Andy Wardley',
- },
- };
-
- sub get_user_projects {
- my $user = shift;
- my @projects = ... # do something to retrieve data
- return \@projects;
- }
-
- my $template = Template->new({
- INCLUDE_PATH => '/home/abw/websrc/src:/home/abw/websrc/lib',
- PRE_PROCESS => 'config',
- });
-
- $template->process($file, $vars)
- || die $template->error();
-
-Here's a sample template file that we might create to build the output
-for this script.
-
-$src/userinfo.html:
-
- [% INCLUDE header
- title = 'Template Toolkit CGI Test'
- %]
-
- <a href="mailto:[% email %]">Email [% me.name %]</a>
-
- <p>This is version [% version %]</p>
-
- <h3>Projects</h3>
- <ul>
- [% FOREACH project IN worklist(me.id) %]
- <li> <a href="[% project.url %]">[% project.name %]</a>
- [% END %]
- </ul>
-
- [% INCLUDE footer %]
-
-This example shows how we've separated the Perl implementation (code) from the
-presentation (HTML). This not only makes them easier to maintain in isolation,
-but also allows the re-use of existing template elements such as headers and
-footers, etc. By using template to create the output of your CGI scripts, you
-can give them the same consistency as your static pages built via
-L<ttree|Template::Tools::ttree> or other means.
-
-Furthermore, we can modify our script so that it processes any one of a
-number of different templates based on some condition. A CGI script to
-maintain a user database, for example, might process one template to
-provide an empty form for new users, the same form with some default
-values set for updating an existing user record, a third template for
-listing all users in the system, and so on. You can use any Perl
-functionality you care to write to implement the logic of your
-application and then choose one or other template to generate the
-desired output for the application state.
-
-=head1 Dynamic Content Generation Via Apache/Mod_Perl Handler
-
-B<NOTE:> the L<Apache::Template> module is available from CPAN and provides a
-simple and easy to use Apache/mod_perl interface to the Template Toolkit.
-Although basic, it implements most, if not all of what is described below, and
-it avoids the need to write your own handler. However, in many cases, you'll
-want to write your own handler to customise processing for your own need, and
-this section will show you how to get started.
-
-The L<Template> module can be used from an Apache/mod_perl handler. Here's an
-example of a typical Apache F<httpd.conf> file:
-
- PerlModule CGI;
- PerlModule Template
- PerlModule MyOrg::Apache::User
-
- PerlSetVar websrc_root /home/abw/websrc
-
- <Location /user/bin>
- SetHandler perl-script
- PerlHandler MyOrg::Apache::User
- </Location>
-
-This defines a location called C</user/bin> to which all requests will
-be forwarded to the C<handler()> method of the C<MyOrg::Apache::User>
-module. That module might look something like this:
-
- package MyOrg::Apache::User;
-
- use strict;
- use vars qw( $VERSION );
- use Apache::Constants qw( :common );
- use Template qw( :template );
- use CGI;
-
- $VERSION = 1.59;
-
- sub handler {
- my $r = shift;
-
- my $websrc = $r->dir_config('websrc_root')
- or return fail($r, SERVER_ERROR,
- "'websrc_root' not specified");
-
- my $template = Template->new({
- INCLUDE_PATH => "$websrc/src/user:$websrc/lib",
- PRE_PROCESS => 'config',
- OUTPUT => $r, # direct output to Apache request
- });
-
- my $params = {
- uri => $r->uri,
- cgi => CGI->new,
- };
-
- # use the path_info to determine which template file to process
- my $file = $r->path_info;
- $file =~ s[^/][];
-
- $r->content_type('text/html');
- $r->send_http_header;
-
- $template->process($file, $params)
- || return fail($r, SERVER_ERROR, $template->error());
-
- return OK;
- }
-
- sub fail {
- my ($r, $status, $message) = @_;
- $r->log_reason($message, $r->filename);
- return $status;
- }
-
-The handler accepts the request and uses it to determine the C<websrc_root>
-value from the config file. This is then used to define an C<INCLUDE_PATH>
-for a new L<Template> object. The URI is extracted from the request and a
-L<CGI> object is created. These are both defined as template variables.
-
-The name of the template file itself is taken from the C<PATH_INFO> element
-of the request. In this case, it would comprise the part of the URL
-coming after C</user/bin>, e.g for C</user/bin/edit>, the template file
-would be C<edit> located in C<$websrc/src/user>. The headers are sent
-and the template file is processed. All output is sent directly to the
-C<print()> method of the Apache request object.
-
-=head1 Using Plugins to Extend Functionality
-
-As we've already shown, it is possible to bind Perl data and functions
-to template variables when creating dynamic content via a CGI script
-or Apache/mod_perl process. The Template Toolkit also supports a
-plugin interface which allows you define such additional data and/or
-functionality in a separate module and then load and use it as
-required with the C<USE> directive.
-
-The main benefit to this approach is that you can load the extension into
-any template document, even those that are processed "statically" by
-C<tpage> or C<ttree>. You I<don't> need to write a Perl wrapper to
-explicitly load the module and make it available via the stash.
-
-Let's demonstrate this principle using the C<DBI> plugin written by Simon
-Matthews (available from CPAN). You can create this template in your C<src>
-directory and process it using C<ttree> to see the results. Of course, this
-example relies on the existence of the appropriate SQL database but you should
-be able to adapt it to your own resources, or at least use it as a
-demonstrative example of what's possible.
-
- [% INCLUDE header
- title = 'User Info'
- %]
-
- [% USE DBI('dbi:mSQL:mydbname') %]
-
- <table border=0 width="100%">
- <tr>
- <th>User ID</th>
- <th>Name</th>
- <th>Email</th>
- </tr>
- [% FOREACH user IN DBI.query('SELECT * FROM user ORDER BY id') %]
- <tr>
- <td>[% user.id %]</td>
- <td>[% user.name %]</td>
- <td>[% user.email %]</td>
- </tr>
- [% END %]
- </table>
-
- [% INCLUDE footer %]
-
-A plugin is simply a Perl module in a known location and conforming to
-a known standard such that the Template Toolkit can find and load it
-automatically. You can create your own plugin by inheriting from the
-L<Template::Plugin> module.
-
-Here's an example which defines some data items (C<foo> and C<people>)
-and also an object method (C<bar>). We'll call the plugin C<FooBar> for
-want of a better name and create it in the C<MyOrg::Template::Plugin::FooBar>
-package. We've added a C<MyOrg> to the regular C<Template::Plugin::*> package
-to avoid any conflict with existing plugins.
-
- package MyOrg::Template::Plugin::FooBar;
- use base 'Template::Plugin'
- our $VERSION = 1.23;
-
- sub new {
- my ($class, $context, @params) = @_;
-
- bless {
- _CONTEXT => $context,
- foo => 25,
- people => [ 'tom', 'dick', 'harry' ],
- }, $class;
- }
-
- sub bar {
- my ($self, @params) = @_;
- # ...do something...
- return $some_value;
- }
-
-The plugin constructor C<new()> receives the class name as the first
-parameter, as is usual in Perl, followed by a reference to something called a
-L<Template::Context> object. You don't need to worry too much about this at
-the moment, other than to know that it's the main processing object for the
-Template Toolkit. It provides access to the functionality of the processor and
-some plugins may need to communicate with it. We don't at this stage, but
-we'll save the reference anyway in the C<_CONTEXT> member. The leading
-underscore is a convention which indicates that this item is private and the
-Template Toolkit won't attempt to access this member. The other members
-defined, C<foo> and C<people> are regular data items which will be made
-available to templates using this plugin. Following the context reference are
-passed any additional parameters specified with the USE directive, such as the
-data source parameter, C<dbi:mSQL:mydbname>, that we used in the earlier DBI
-example.
-
-If you don't or can't install it to the regular place for your Perl
-modules (perhaps because you don't have the required privileges) then
-you can set the PERL5LIB environment variable to specify another location.
-If you're using C<ttree> then you can add the following line to your
-configuration file instead.
-
-$HOME/.ttreerc:
-
- perl5lib = /path/to/modules
-
-One further configuration item must be added to inform the toolkit of
-the new package name we have adopted for our plugins:
-
-$HOME/.ttreerc:
-
- plugin_base = 'MyOrg::Template::Plugin'
-
-If you're writing Perl code to control the L<Template> modules directly,
-then this value can be passed as a configuration parameter when you
-create the module.
-
- use Template;
-
- my $template = Template->new({
- PLUGIN_BASE => 'MyOrg::Template::Plugin'
- });
-
-Now we can create a template which uses this plugin:
-
- [% INCLUDE header
- title = 'FooBar Plugin Test'
- %]
-
- [% USE FooBar %]
-
- Some values available from this plugin:
- [% FooBar.foo %] [% FooBar.bar %]
-
- The users defined in the 'people' list:
- [% FOREACH uid = FooBar.people %]
- * [% uid %]
- [% END %]
-
- [% INCLUDE footer %]
-
-The C<foo>, C<bar>, and C<people> items of the FooBar plugin are
-automatically resolved to the appropriate data items or method calls
-on the underlying object.
-
-Using this approach, it is possible to create application
-functionality in a single module which can then be loaded and used on
-demand in any template. The simple interface between template
-directives and plugin objects allows complex, dynamic content to be
-built from a few simple template documents without knowing anything
-about the underlying implementation.
-
-=head1 AUTHOR
-
-Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
-
-=head1 COPYRIGHT
-
-Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
-
-This module is free software; you can redistribute it and/or
-modify it under the same terms as Perl itself.
-
-=cut
-
-# Local Variables:
-# mode: perl
-# perl-indent-level: 4
-# indent-tabs-mode: nil
-# End:
-#
-# vim: expandtab shiftwidth=4:
<div class="col-md-12">
<div class="card box-shadow h-md-250">
<div class="card-body d-flex flex-column align-items-start">
- <strong class="d-inline-block mb-2 text-primary">Events</strong>
+ <strong class="d-inline-block mb-2 text-primary">Nächst Evenementer...</strong>
<div style="width: 100%;text-align: center;">
- <p class="card-text"><span class="text-muted">13. Abrëll 2018</span><br/>Scampis à l'ail<br/><span class="text-muted">Café Centenaire - Betebuerg</span></p>
- <p class="card-text"><span class="text-muted">13. Mee 2018</span><br/>Fraizait-Fëschen<br/><span class="text-muted">Weiher - Leudelange-Abweiler</span></p>
- <p class="card-text"><span class="text-muted">2.-3. Juni 2018</span><br/>Autocross<br/><span class="text-muted">Helleng</span></p>
+
+ [% FOREACH nevent = webdb.query("SELECT name,location,to_char(startdate,'DD.MM.YYYY') || case when enddate is not null then ' - ' || to_char(enddate,'DD.MM.YYYY') else '' end as daterange FROM events where startdate >= CURRENT_DATE order by startdate,enddate limit 2;") %]
+ <p class="card-text"><span class="text-muted">[% nevent.daterange %]</span><br/>[% nevent.name %]<br/><span class="text-muted">[% nevent.location %]</span></p>
+ [% END %]
+
</div>
+ <br/>
<a class="btn btn-primary js-scroll-trigger ml-auto" href="#events">Evenementer...</a>
</div>
</div>
</div>
- <div class="col-md-12">
+ <!--<div class="col-md-12">
<div class="card box-shadow h-md-250">
<div class="card-body d-flex flex-column align-items-start">
<strong class="d-inline-block mb-2 text-primary">News</strong>
<a class="btn btn-primary js-scroll-trigger ml-auto" href="#gallery">Biller Gallerie</a>
</div>
</div>
- </div>
+ </div>-->
</div>
</div>
</div>
</div>
</section>
-<!-- <header class="masthead">
- <div class="header-content">
- <div class="header-content-inner">
- <h1 id="homeHeading"></h1>
- <hr/>
- <p></p>
- <a class="btn btn-primary btn-xl js-scroll-trigger" href="#iwwertons">Fann méi eraus</a>
- </div>
- </div>
- </header> -->
+
\ No newline at end of file
</div>
</div>
<div class="container">
- <div class="event-gallery row justify-content-md-center">
-
-
- <div class="card" style="width: 18rem;">
- <a title="Evenementer" href="img/events/Affiche_scampis_a_l_ail_20180413.jpg" data-footer="13.04.2018 - Café Centenaire Beetebuerg" data-title="Scampis à l'ail">
- <img class="card-img-top" src="img/events/Affiche_scampis_a_l_ail_20180413.jpg" alt="Scampis à l'ail - 13.04.2018 - Café Centenaire Beetebuerg">
- </a>
-
- </div>
- <div class="card" style="width: 18rem;">
- <a title="Evenementer" href="img/events/Feschen_20180513.jpg" data-footer="n -13.05.2018 - Weiher Leudelange-Abweiler" data-title="Fraizait-Feschen">
- <img class="card-img-top" src="img/events/Feschen_20180513.jpg" alt="Fraizait-Feschen -13.05.2018 - Weiher Leudelange-Abweiler">
- </a>
- </div>
- <div class="card" style="width: 18rem;">
- <a title="Evenementer" href="img/events/autocross_hellange_2018.jpg" data-footer="2-3.06.2018 - Hellange" data-title="Autocross">
- <img class="card-img-top" src="img/events/autocross_hellange_2018.jpg" alt="Autocross - 2-3.06.2018 - Hellange">
- </a>
- </div>
+ <div class="row justify-content-center">
+ [% FOREACH event = webdb.query("SELECT name,location,to_char(startdate,'DD.MM.YYYY') || case when enddate is not null then ' - ' || to_char(enddate,'DD.MM.YYYY') else '' end as daterange FROM events order by startdate,enddate,starttime,endtime;") %]
+
+ <div class="col-sm-12">
+ <div class="card">
+ <div class="card-body">
+ <h4 class="card-title">[% event.name %]</h4>
+ <p><span class="font-weight-bold">[% event.daterange %]</span> - [% event.location %]</p>
+ </div>
+ </div>
+ </div>
+
+ [% END %]
</div>
</div>
+[% USE webdb = DBI(dbconn, dbuser, dbpass) %]
<!DOCTYPE html>
<html lang="en">
<head>