The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
[%#
  # IMPORTANT NOTE
  #   This documentation is generated automatically from source
  #   templates.  Any changes you make here may be lost.
  # 
  #   The 'docsrc' documentation source bundle is available for download
  #   from http://www.template-toolkit.org/docs.html and contains all
  #   the source templates, XML files, scripts, etc., from which the
  #   documentation for the Template Toolkit is built.
-%]
[% META book = 'Manual'
        page = 'Internals'
%]
[%  WRAPPER toc;
	PROCESS tocitem 
	        title ="DESCRIPTION"
                subs  = [
                    "Outside Looking In",
		    "Inside Looking Out"
		];
	PROCESS tocitem 
	        title ="HACKING ON THE TEMPLATE TOOLKIT"
                subs  = [];
	PROCESS tocitem 
	        title ="AUTHOR"
                subs  = [];
	PROCESS tocitem 
	        title ="VERSION"
                subs  = [];
	PROCESS tocitem 
	        title ="COPYRIGHT"
                subs  = [];
    END
%]
<!-- Pod to HTML conversion by the Template Toolkit version 2 -->
[% WRAPPER section
    title="DESCRIPTION"
-%][% WRAPPER subsection
   title = "Outside Looking In"
-%]<p>
The <b>Template</b> module is simply a front end module which creates and
uses a Template::Service and pipes the output wherever you want it to
go (STDOUT by default, or maybe a file, scalar, etc).  The
Apache::Template module (available separately from CPAN) is another
front end.  That creates a Template::Service::Apache object, calls on
it as required and sends the output back to the relevant
Apache::Request object.
</p>
<p>
These front-end modules are really only there to handle any specifics
of the environment in which they're being used.  The Apache::Template
front end, for example, handles Apache::Request specifics and
configuration via the httpd.conf.  The regular Template front-end
deals with STDOUT, variable refs, etc.  Otherwise it is
Template::Service (or subclass) which does all the work.
</p>
<p>
The <b>Template::Service</b> 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.  &quot;Have
a good time, all the time&quot;, that's our motto.
</p>
<p>
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.  Template::Service hides that all
away and makes everything look simple to the outsider.  It provides
extra features, like PRE_PROCESS, PROCESS and POST_PROCESS, and also
provides the error recovery mechanism via ERROR.  You ask it to
process a template and it takes care of everything for you.  The 
Template::Service::Apache module goes a little bit further, adding 
some extra headers to the Apache::Request, setting a few extra template
variables, and so on.
</p>
<p>
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 process() method and schedules the named template
specified as an argument, and possibly several other templates
(PRE_PROCESS, etc) to be processed in order.  It doesn't actually
process the templates itself, but instead makes a process() call
against a Template::Context object.
</p>
<p>
<b>Template::Context</b> 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.  
</p>
<p>
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
Template::Provider objects (the LOAD_TEMPLATES posse) who themselves
might get involved with a 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 template()
method.  You call it passing a template name as an argument, and it
returns a compiled template in the form of a Template::Document
object, or otherwise raises an exception.
</p>
<p>
A <b>Template::Document</b> is a thin object wrapper around a compiled 
template subroutine.  The object implements a process() method which
performs a little bit of housekeeping and then calls the template 
subroutine.  The object also defines template metadata (defined in 
<code>'[% tt_start_tag %] META ... [% tt_end_tag %]'</code> directives) and has a block() method which returns
a hash of any additional <code>'[% tt_start_tag %] BLOCK xxxx [% tt_end_tag %]'</code> definitions found in the 
template source.
</p>
<p>
So the context fetches a compiled document via its own 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 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.
</p>
<p>
What we're trying to say here is this:  not only does the Template::Context
object receive calls from the <i>outside</i>, 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>, i.e. those originating in template
directives of the form <code>'[% tt_start_tag %] PROCESS template [% tt_end_tag %]'</code>.
</p>
<p>
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.
</p>
<pre>     ,--------.
     | Caller |	    use Template;
     `--------'     my $tt = Template-&gt;new( ... );
          |	    $tt-&gt;process($template, \%vars);
          |                                                     Outside
  - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - T T 
	  |         package Template;                            Inside
          V
    +----------+    sub process($template, \%vars) {
    | Template |	$out = $self-&gt;SERVICE-&gt;process($template, $vars);
    +----------+	print $out or send it to $self-&gt;OUTPUT;
          |	    }
          |
          |         package Template::Service;
          |
	  |	    sub process($template, \%vars) {
	  |		try {
    +----------+	    foreach $p in @self-&gt;PRE_PROCESS
    | Service  |	        $self-&gt;CONTEXT-&gt;process($p, $vars);
    +----------+
	  |		    $self-&gt;CONTEXT-&gt;process($template, $vars);
          |
	  |		    foreach $p @self-&gt;POST_PROCESS
	  |			$self-&gt;CONTEXT-&gt;process($p, $vars);
	  |		}
          |  		catch {
	  |		    $self-&gt;CONTEXT-&gt;process($self-&gt;ERROR);
	  |		}
	  |	    }
          |
          V         package Template::Context;
    +----------+    
    | Context  |    sub process($template, \%vars) {
    +----------+	# fetch compiled template
	  |		$template = $self-&gt;template($template)
          |             # update stash
          |	        $self-&gt;STASH-&gt;update($vars);
          |	        # process template
          |             $template-&gt;process($self)
          |         }
          V     
    +----------+    package Template::Document;
    | Document |    
    +----------+    sub process($context) {
			$output = &amp;{ $self-&gt;BLOCK }($context);
		    }
        </pre>
[%- END %]
[% WRAPPER subsection
   title = "Inside Looking Out"
-%]<p>
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.
</p>
<pre>    sub my_compiled_template {
	return &quot;This is a compiled template.\n&quot;;
    }</pre>
<p>
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 die().
</p>
<pre>    sub my_todo_template {
	die &quot;This template not yet implemented\n&quot;;
    }</pre>
<p>
If it wants to get fancy, it can raise an error as a
Template::Exception object.  An exception object is really just a
convenient wrapper for the 'type' and 'info' fields.
</p>
<pre>    sub my_solilique_template {
	die (Template::Exception-&gt;new('yorrick', 'Fellow of infinite jest'));
    }</pre>
<p>
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 Template::Context object.  It is through this context object that
template code can access the features of the Template Toolkit.
</p>
<p>
We described earlier how the Template::Service object calls on
Template::Context to handle a process() request from the <i>outside</i>.
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</i>.
</p>
<pre>    sub my_process_template {
	my $context = shift;</pre>
<pre>	my $output = $context-&gt;process('header', { title =&gt; 'Hello World' })
		   . &quot;\nsome content\n&quot;
		   . $context-&gt;process('footer');
    }</pre>
<p>
This is then roughly equivalent to a source template something
like this:
</p>
<pre>    [% tt_start_tag %] PROCESS header
	title = 'Hello World'
    [% tt_end_tag %]
    some content
    [% tt_start_tag %] PROCESS footer [% tt_end_tag %]</pre>
<p>
Template variables are stored in, and managed by a <b>Template::Stash</b>
object.  This is a blessed hash array in which template variables are
defined.  The object wrapper provides get() and set() method which
implement all the magical.variable.features of the Template Toolkit.
</p>
<p>
Each context object has its own stash, a reference to which can be
returned by the appropriately named stash() method.  So to print the
value of some template variable, or for example, to represent the
following source template:
</p>
<pre>    &lt;title&gt;[% tt_start_tag %] title [% tt_end_tag %]&lt;/title&gt;</pre>
<p>
we might have a subroutine definition something like this:
</p>
<pre>    sub {
	my $context = shift;
	my $stash = $context-&gt;stash();
	return '&lt;title&gt;' . $stash-&gt;get('title') . '&lt;/title&gt;';
    }</pre>
<p>
The stash get() method hides the details of the underlying variable
types, automatically calling code references, checking return values,
and performing other such tricks.  If '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().
</p>
<pre>    [% tt_start_tag %] title('The Cat Sat on the Mat') [% tt_end_tag %]</pre>
<p>
This translates to the stash get() call:
</p>
<pre>    $stash-&gt;get([ 'title', ['The Cat Sat on the Mat'] ]);</pre>
<p>
Dotted compound variables can be requested by passing a single 
list reference to the 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.
</p>
<pre>    [% tt_start_tag %] foo(1, 2).bar(3, 4).baz(5) [% tt_end_tag %]</pre>
<p>
is thus equivalent to
</p>
<pre>    $stash-&gt;get([ foo =&gt; [1,2], bar =&gt; [3,4], baz =&gt; [5] ]);</pre>
<p>
If there aren't any arguments for an element, you can specify an 
empty, zero or null argument list.
</p>
<pre>    [% tt_start_tag %] foo.bar [% tt_end_tag %]
    $stash-&gt;get([ 'foo', 0, 'bar', 0 ]);</pre>
<p>
The set() method works in a similar way.  It takes a variable 
name and a variable value which should be assigned to it.
</p>
<pre>    [% tt_start_tag %] x = 10 [% tt_end_tag %]         
    $stash-&gt;set('x', 10);</pre>
<pre>    [% tt_start_tag %] x.y = 10 [% tt_end_tag %]
    $stash-&gt;set([ 'x', 0, 'y', 0 ], 10);</pre>
<p>
So the stash gives us access to template variables and the context
provides the higher level functionality.  Alongside the process()
method lies the include() method.  Just as with the PROCESS / INCLUDE
directives, the key difference is in variable localisation.  Before
processing a template, the process() method simply updates the stash
to set any new variable definitions, overwriting any existing values.
In contrast, the include() method creates a copy of the existing
stash, in a process known as <i>cloning</i> 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 include()
method restores the previous variable state by <i>decloning</i> the stash.
</p>
<p>
The context also provides an insert() method to implement the INSERT 
directive, but no wrapper() method.  This functionality can be implemented
by rewriting the Perl code and calling include().
</p>
<pre>    [% tt_start_tag %] WRAPPER foo -[% tt_end_tag %]
       blah blah [% tt_start_tag %] x [% tt_end_tag %]
    [% tt_start_tag %]- END [% tt_end_tag %]</pre>
<pre>    $context-&gt;include('foo', {
	content =&gt; 'blah blah ' . $stash-&gt;get('x'),
    });</pre>
<p>
Other than the template processing methods process(), include() and insert(),
the context defines methods for fetching plugin objects, plugin(), and 
filters, filter().
</p>
<pre>    [% tt_start_tag %] USE foo = Bar(10) [% tt_end_tag %]</pre>
<pre>    $stash-&gt;set('foo', $context-&gt;plugin('Bar', [10]));</pre>
<pre>    [% tt_start_tag %] FILTER bar(20) [% tt_end_tag %]
       blah blah blah
    [% tt_start_tag %] END [% tt_end_tag %]</pre>
<pre>    my $filter = $context-&gt;filter('bar', [20]);
    &amp;$filter('blah blah blah');</pre>
<p>
Pretty much everything else you might want to do in a template can be done
in Perl code.  Things like IF, UNLESS, FOREACH and so on all have direct
counterparts in Perl.
</p>
<pre>    [% tt_start_tag %] IF msg [% tt_end_tag %]
       Message: [% tt_start_tag %] msg [% tt_end_tag %]
    [% tt_start_tag %] END [% tt_end_tag %];</pre>
<pre>    if ($stash-&gt;get('msg')) {
	$output .=  'Message: ';
	$output .= $stash-&gt;get('msg');
    }</pre>
<p>
The best way to get a better understanding of what's going on underneath
the hood is to set the <code>'$Template::Parser::DEBUG'</code> 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 STDERR.  You'll 
probably also want to set the <code>'$Template::Directive::PRETTY'</code> option to
have the Perl pretty-printed for human consumption.
</p>
<pre>    use Template;
    use Template::Parser;
    use Template::Directive;
    
    $Template::Parser::DEBUG = 1;
    $Template::Directive::PRETTY = 1;
    
    my $template = Template-&gt;new();
    $template-&gt;process(\*DATA, { cat =&gt; 'dog', mat =&gt; 'log' });
    
    __DATA__
    The [% tt_start_tag %] cat [% tt_end_tag %] sat on the [% tt_start_tag %] mat [% tt_end_tag %]</pre>
<p>
The output sent to STDOUT remains as you would expect:
</p>
<pre>    The dog sat on the log</pre>
<p>
The output sent to STDERR would look something like this:
</p>
<pre>    compiled main template document block:
    sub {
    	my $context = shift || die &quot;template sub called without context\n&quot;;
    	my $stash   = $context-&gt;stash;
    	my $output  = '';
    	my $error;
    	
    	eval { BLOCK: {
    	    $output .=  &quot;The &quot;;
    	    $output .=  $stash-&gt;get('cat');
    	    $output .=  &quot; sat on the &quot;;
    	    $output .=  $stash-&gt;get('mat');
    	    $output .=  &quot;\n&quot;;
    	} };
    	if ($@) {
    	    $error = $context-&gt;catch($@, \$output);
    	    die $error unless $error-&gt;type eq 'return';
    	}
    
    	return $output;
    }</pre>
[%- END %]
[%- END %]
[% WRAPPER section
    title="HACKING ON THE TEMPLATE TOOLKIT"
-%]<p>
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!  
</p>
<p>
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.
</p>
<p>
When you start to hack on the Template Toolkit, please make sure you
start from the latest developer release.  Stable releases are uploaded
to CPAN and have all-numerical version numbers, e.g. 2.04, 2.05. 
Developer releases are available from the Template Toolkit web site
and have a character suffix on the version, e.g. 2.04a, 2.04b, etc.
</p>
<p>
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 't' sub-directory, or by adding a new test script of your own.
And of course, run <code>'make test'</code> to ensure that all the tests pass
with your new code.
</p>
<p>
Don't forget that any files you do add will need to be added to the
MANIFEST.  Running '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.
</p>
<p>
Documentation is often something that gets overlooked but it's just
as important as the code.  If you're updating existing documentation
then you should download the 'docsrc' bundle from which all the 
Template Toolkit documentation is built and make your changes in there.
It's also available from the Template Toolkit web site.  See the 
README distributed in the archive for further information.
</p>
<p>
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</i>
write it all in one piece at the end of the file, <i>after</i> the code
(just look at any other 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).
</p>
<p>
Aesthetics aside, if I do want to extract the documentation into the
docsrc bundle then it's easy for me to do it if it's all written in
one chunk and extremely tedious if not.  So for practical reasons
alone, please keep Perl and POD sections separate.  Comment blocks
within the code are of course welcome.
</p>
<p>
To share your changes with the rest of the world, you'll need to 
prepare a patch file.  To do this you should have 2 directories
side-by-side, one which is the original, unmodified distribution
directory for the latest developer release, and the other is a
copy of that same directory which includes your changes. 
</p>
<p>
The following example shows a typical hacking session.  First we
unpack the latest developer release.
</p>
<pre>    $ tar zxf Template-Toolkit-2.05c.tar.gz</pre>
<p>
At this point, it's a good idea to rename the directory to give 
some indicate of what it contains.
</p>
<pre>    $ mv Template-Toolkit-2.05c Template-Toolkit-2.05c-abw-xyz-hack</pre>
<p>
Then go hack!
</p>
<pre>    $ cd Template-Toolkit-2.05c-abw-xyz-hack</pre>
<pre>      [ hacking ]</pre>
<pre>    $ cd ..</pre>
<p>
When you're all done and ready to prepare a patch, unpack the 
distribution archive again so that you've got the original to 
diff against your new code.
</p>
<pre>    $ tar zxf Template-Toolkit-2.05c.tar.gz</pre>
<p>
You should now have an original distribution directory and a modified
version of that same directory, side-by-side.  
</p>
<pre>    $ ls
    Template-Toolkit-2.05c  Template-Toolkit-2.05c-abw-xyz-hack</pre>
<p>
Now run diff and save the output into an appropriately named patch
file.  
</p>
<pre>    $ diff -Naur Template-Toolkit-2.05c Template-Toolkit-2.05c-abw-xyz-hack &gt; patch-TT205c-abw-xyz-hack</pre>
<p>
You can then post the generated patch file to the mailing list, 
describing what it does, why it does it, how it does it and any 
other relevant information.
</p>
<p>
If you want to apply someone else's patch then you should start with the
same original distribution source on which the patch is based.  From within
the root of the distribution, run 'patch' feeding in the patch file as 
standard input.  The 'p1' option is required to strip the first element
of the path name (e.g. Template-Toolkit-2.05c/README becomes README which
is then the correct path).
</p>
<pre>    $ tar zxf Template-Toolkit-2.05c.tar.gz
    $ cd Template-Toolkit-2.05c
    $ patch -p1 &lt; ../patch-TT205c-abw-xyz-hack</pre>
<p>
The output generated by 'patch' should be something like the following:
</p>
<pre>    patching file README
    patching file lib/Template.pm
    patching file lib/Template/Provider.pm
    patching file t/provider.t</pre>
[%- END %]
[% WRAPPER section
    title="AUTHOR"
-%]<p>
Andy Wardley &lt;abw@wardley.org&gt;
</p>
<p>
[% ttlink('http://wardley.org/', 'http://wardley.org/') -%]
</p>
[%- END %]
[% WRAPPER section
    title="VERSION"
-%]<p>
Template Toolkit version 2.19, released on 27 April 2007.
</p>
[%- END %]
[% WRAPPER section
    title="COPYRIGHT"
-%]<pre>  Copyright (C) 1996-2007 Andy Wardley.  All Rights Reserved.</pre>
<p>
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
</p>
[%- END %]