Mini Shell

Direktori : /home/.cpanm/work/1731937184.9052/Template-Toolkit-3.102/blib/man3/
Upload File :
Current File : //home/.cpanm/work/1731937184.9052/Template-Toolkit-3.102/blib/man3/Template::Manual::Internals.3pm

.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.42)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  \*(C+ will
.\" give a nicer C++.  Capital omega is used to do unbreakable dashes and
.\" therefore won't be available.  \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
.    ds C`
.    ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el       .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
.    if \nF \{\
.        de IX
.        tm Index:\\$1\t\\n%\t"\\$2"
..
.        if !\nF==2 \{\
.            nr % 0
.            nr F 2
.        \}
.    \}
.\}
.rr rF
.\" ========================================================================
.\"
.IX Title "Template::Manual::Internals 3"
.TH Template::Manual::Internals 3 "2024-06-21" "perl v5.32.1" "User Contributed Perl Documentation"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
Template::Manual::Internals \- Template Toolkit internals
.SH "Introduction"
.IX Header "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.
.PP
If that doesn't sound like you then you probably don't need to read this.
There is no test afterwards.
.SH "Outside Looking In"
.IX Header "Outside Looking In"
The Template module is simply a front end module which creates and
uses a Template::Service and pipes the output wherever you want it to
go (\f(CW\*(C`STDOUT\*(C'\fR by default, or maybe a file, scalar, etc).  The
\&\f(CW\*(C`Apache::Template\*(C'\fR module (available separately from \s-1CPAN\s0) is another
front end.  That creates a \f(CW\*(C`Template::Service::Apache\*(C'\fR object, calls on
it as required and sends the output back to the relevant
\&\f(CW\*(C`Apache::Request\*(C'\fR object.
.PP
These front-end modules are really only there to handle any specifics
of the environment in which they're being used.  The \f(CW\*(C`Apache::Template\*(C'\fR
front end, for example, handles \f(CW\*(C`Apache::Request\*(C'\fR specifics and
configuration via the \fIhttpd.conf\fR.  The regular Template front-end
deals with \f(CW\*(C`STDOUT\*(C'\fR, variable refs, etc.  Otherwise it is
Template::Service (or subclass) which does all the work.
.PP
The 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.  \*(L"Have
a good time, all the time\*(R", that's our motto.
.PP
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 \f(CW\*(C`PRE_PROCESS\*(C'\fR, \f(CW\*(C`PROCESS\*(C'\fR and
\&\f(CW\*(C`POST_PROCESS\*(C'\fR, and also provides the error recovery mechanism via \f(CW\*(C`ERROR\*(C'\fR.
You ask it to process a template and it takes care of everything for you. The
\&\f(CW\*(C`Template::Service::Apache\*(C'\fR module goes a little bit further, adding some extra
headers to the Apache::Request, setting a few extra template variables, and so
on.
.PP
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
\&\fBprocess()\fR method and schedules the named
template specified as an argument, and possibly several other templates
(\f(CW\*(C`PRE_PROCESS\*(C'\fR, etc) to be processed in order. It doesn't actually process
the templates itself, but instead makes a
\&\fBprocess()\fR call against a Template::Context
object.
.PP
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.
.PP
Given a template name (or perhaps a reference to a scalar or file
handle) the context \fBprocess()\fR 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 \f(CW\*(C`LOAD_TEMPLATES\*(C'\fR posse) who themselves
might get involved with a Template::Parser to help turn source
templates into executable Perl code (but more on that later).
.PP
Thankfully, all of this complexity is hidden away behind a simple
\&\fBtemplate()\fR 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.
.PP
A Template::Document is a thin object wrapper around a compiled template
subroutine. The object implements a \fBprocess()\fR
method which performs a little bit of housekeeping and then calls the template
subroutine. The object also defines template metadata (defined in \f(CW\*(C`[% META
\&... %]\*(C'\fR directives) and has a \fBblock()\fR method
which returns a hash of any additional \f(CW\*(C`[% BLOCK xxxx %]\*(C'\fR definitions found
in the template source.
.PP
So the context fetches a compiled document via its own
\&\fBtemplate()\fR 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 \fBprocess()\fR 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.
.PP
What we're trying to say here is this:  not only does the Template::Context
object receive calls from the \fIoutside\fR, i.e. those originating in user
code calling the \fBprocess()\fR method on a Template object, but it also
receives calls from the \fIinside\fR, i.e. those originating in template
directives of the form \f(CW\*(C`[% PROCESS template %]\*(C'\fR.
.PP
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.
.PP
.Vb 10
\&     ,\-\-\-\-\-\-\-\-.
\&     | Caller |     use Template;
\&     \`\-\-\-\-\-\-\-\-\*(Aq     my $tt = Template\->new( ... );
\&          |         $tt\->process($template, \e%vars);
\&          |                                                     Outside
\&    \- \- \- | \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- \- T T
\&          |         package Template;                            Inside
\&          V
\&    +\-\-\-\-\-\-\-\-\-\-+    sub process($template, \e%vars) {
\&    | Template |        $out = $self\->SERVICE\->process($template, $vars);
\&    +\-\-\-\-\-\-\-\-\-\-+        print $out or send it to $self\->OUTPUT;
\&          |         }
\&          |
\&          |         package Template::Service;
\&          |
\&          |         sub process($template, \e%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, \e%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);
\&                    }
.Ve
.SH "Inside Looking Out"
.IX Header "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.
.PP
.Vb 3
\&    sub my_compiled_template {
\&        return "This is a compiled template.\en";
\&    }
.Ve
.PP
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 \f(CW\*(C`die()\*(C'\fR.
.PP
.Vb 3
\&    sub my_todo_template {
\&        die "This template not yet implemented\en";
\&    }
.Ve
.PP
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 '\f(CW\*(C`type\*(C'\fR' and '\f(CW\*(C`info\*(C'\fR' fields.
.PP
.Vb 3
\&    sub my_solilique_template {
\&        die (Template::Exception\->new(\*(Aqyorrick\*(Aq, \*(AqFellow of infinite jest\*(Aq));
\&    }
.Ve
.PP
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.
.PP
We described earlier how the Template::Service object calls on
Template::Context to handle a \fBprocess()\fR
request from the \fIoutside\fR. 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 \fIinside\fR.
.PP
.Vb 6
\&    sub my_process_template {
\&        my $context = shift;
\&        my $output = $context\->process(\*(Aqheader\*(Aq, { title => \*(AqHello World\*(Aq })
\&                   . "\ensome content\en"
\&                   . $context\->process(\*(Aqfooter\*(Aq);
\&    }
.Ve
.PP
This is then roughly equivalent to a source template something
like this:
.PP
.Vb 5
\&    [% PROCESS header
\&        title = \*(AqHello World\*(Aq
\&    %]
\&    some content
\&    [% PROCESS footer %]
.Ve
.PP
Template variables are stored in, and managed by a Template::Stash object.
This is a blessed hash array in which template variables are defined. The
object wrapper provides \fBget()\fR and
\&\fBset()\fR method which implement all the
\&\fImagical.variable.features\fR of the Template Toolkit.
.PP
Each context object has its own stash, a reference to which can be returned by
the appropriately named \fBstash()\fR method. So to
print the value of some template variable, or for example, to represent the
following source template:
.PP
.Vb 1
\&    <title>[% title %]</title>
.Ve
.PP
we might have a subroutine definition something like this:
.PP
.Vb 5
\&    sub {
\&        my $context = shift;
\&        my $stash = $context\->stash();
\&        return \*(Aq<title>\*(Aq . $stash\->get(\*(Aqtitle\*(Aq) . \*(Aq</title>\*(Aq;
\&    }
.Ve
.PP
The stash \fBget()\fR method hides the details of the
underlying variable types, automatically calling code references, checking
return values, and performing other such tricks. If '\f(CW\*(C`title\*(C'\fR' happens to be
bound to a subroutine then we can specify additional parameters as a list
reference passed as the second argument to \fBget()\fR.
.PP
.Vb 1
\&    [% title(\*(AqThe Cat Sat on the Mat\*(Aq) %]
.Ve
.PP
This translates to the stash call:
.PP
.Vb 1
\&    $stash\->get([ \*(Aqtitle\*(Aq, [\*(AqThe Cat Sat on the Mat\*(Aq] ]);
.Ve
.PP
Dotted compound variables can be requested by passing a single
list reference to the \f(CW\*(C`get()\*(C'\fR 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.
.PP
.Vb 1
\&    [% foo(1, 2).bar(3, 4).baz(5) %]
.Ve
.PP
is thus equivalent to
.PP
.Vb 1
\&    $stash\->get([ foo => [1,2], bar => [3,4], baz => [5] ]);
.Ve
.PP
If there aren't any arguments for an element, you can specify an
empty, zero or null argument list.
.PP
.Vb 2
\&    [% foo.bar %]
\&    $stash\->get([ \*(Aqfoo\*(Aq, 0, \*(Aqbar\*(Aq, 0 ]);
.Ve
.PP
The \fBset()\fR method works in a similar way. It takes a
variable name and a variable value which should be assigned to it.
.PP
.Vb 2
\&    [% x = 10 %]
\&    $stash\->set(\*(Aqx\*(Aq, 10);
\&
\&    [% x.y = 10 %]
\&    $stash\->set([ \*(Aqx\*(Aq, 0, \*(Aqy\*(Aq, 0 ], 10);
.Ve
.PP
So the stash gives us access to template variables and the context provides
the higher level functionality.
.PP
Alongside the \fBprocess()\fR method lies the
\&\fBinclude()\fR method. Just as with the \f(CW\*(C`PROCESS\*(C'\fR /
\&\f(CW\*(C`INCLUDE\*(C'\fR directives, the key difference is in variable localisation. Before
processing a template, the \f(CW\*(C`process()\*(C'\fR method simply updates the stash to set
any new variable definitions, overwriting any existing values. In contrast,
the \f(CW\*(C`include()\*(C'\fR method creates a copy of the existing stash, in a process known
as \fIcloning\fR 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 \f(CW\*(C`include()\*(C'\fR method restores the previous variable state by \fIdecloning\fR the
stash.
.PP
The context also provides an \fBinsert()\fR method to
implement the \f(CW\*(C`INSERT\*(C'\fR directive, but no \f(CW\*(C`wrapper()\*(C'\fR method. This functionality
can be implemented by rewriting the Perl code and calling \f(CW\*(C`include()\*(C'\fR.
.PP
.Vb 3
\&    [% WRAPPER foo \-%]
\&       blah blah [% x %]
\&    [%\- END %]
\&
\&    $context\->include(\*(Aqfoo\*(Aq, {
\&        content => \*(Aqblah blah \*(Aq . $stash\->get(\*(Aqx\*(Aq),
\&    });
.Ve
.PP
Other than the template processing methods \f(CW\*(C`process()\*(C'\fR, \f(CW\*(C`include()\*(C'\fR and
\&\f(CW\*(C`insert()\*(C'\fR, the context defines methods for fetching plugin objects,
\&\fBplugin()\fR, and filters,
\&\fBfilter()\fR.
.PP
.Vb 2
\&    # TT USE directive
\&    [% USE foo = Bar(10) %]
\&
\&    # equivalent Perl
\&    $stash\->set(\*(Aqfoo\*(Aq, $context\->plugin(\*(AqBar\*(Aq, [10]));
\&
\&    # TT FILTER block
\&    [% FILTER bar(20) %]
\&       blah blah blah
\&    [% END %]
\&
\&    # equivalent Perl
\&    my $filter = $context\->filter(\*(Aqbar\*(Aq, [20]);
\&    &$filter(\*(Aqblah blah blah\*(Aq);
.Ve
.PP
Pretty much everything else you might want to do in a template can be done in
Perl code. Things like \f(CW\*(C`IF\*(C'\fR, \f(CW\*(C`UNLESS\*(C'\fR, \f(CW\*(C`FOREACH\*(C'\fR and so on all have direct
counterparts in Perl.
.PP
.Vb 4
\&    # TT IF directive
\&    [% IF msg %]
\&       Message: [% msg %]
\&    [% END %];
\&
\&    # equivalent Perl
\&    if ($stash\->get(\*(Aqmsg\*(Aq)) {
\&        $output .=  \*(AqMessage: \*(Aq;
\&        $output .= $stash\->get(\*(Aqmsg\*(Aq);
\&    }
.Ve
.PP
The best way to get a better understanding of what's going on underneath
the hood is to set the \f(CW$Template::Parser::DEBUG\fR 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 \f(CW\*(C`STDERR\*(C'\fR.  You'll
probably also want to set the \f(CW$Template::Directive::PRETTY\fR option to
have the Perl pretty-printed for human consumption.
.PP
.Vb 3
\&    use Template;
\&    use Template::Parser;
\&    use Template::Directive;
\&
\&    $Template::Parser::DEBUG = 1;
\&    $Template::Directive::PRETTY = 1;
\&
\&    my $template = Template\->new();
\&    $template\->process(\e*DATA, { cat => \*(Aqdog\*(Aq, mat => \*(Aqlog\*(Aq });
\&
\&    _\|_DATA_\|_
\&    The [% cat %] sat on the [% mat %]
.Ve
.PP
The output sent to \f(CW\*(C`STDOUT\*(C'\fR remains as you would expect:
.PP
.Vb 1
\&    The dog sat on the log
.Ve
.PP
The output sent to \f(CW\*(C`STDERR\*(C'\fR would look something like this:
.PP
.Vb 6
\&    compiled main template document block:
\&    sub {
\&        my $context = shift || die "template sub called without context\en";
\&        my $stash   = $context\->stash;
\&        my $output  = \*(Aq\*(Aq;
\&        my $error;
\&
\&        eval { BLOCK: {
\&            $output .=  "The ";
\&            $output .=  $stash\->get(\*(Aqcat\*(Aq);
\&            $output .=  " sat on the ";
\&            $output .=  $stash\->get(\*(Aqmat\*(Aq);
\&            $output .=  "\en";
\&        } };
\&        if ($@) {
\&            $error = $context\->catch($@, \e$output);
\&            die $error unless $error\->type eq \*(Aqreturn\*(Aq;
\&        }
\&
\&        return $output;
\&    }
.Ve
.SH "Hacking on the Template Toolkit"
.IX Header "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 \s-1TODO\s0 list, then by all
means go ahead and do it!
.PP
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.
.PP
The source code repository for the Template Toolkit is hosted at Github.
.PP
.Vb 1
\&    https://github.com/abw/Template2
.Ve
.PP
Clone the repository, make your changes, commit them, then send a pull
request.
.PP
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 \f(CW\*(C`t\*(C'\fR sub-directory, or by adding a new test script of your own.
And of course, run \f(CW\*(C`make test\*(C'\fR to ensure that all the tests pass
with your new code.
.PP
Don't forget that any files you do add will need to be added to the
\&\s-1MANIFEST.\s0  Running \f(CW\*(C`make manifest\*(C'\fR 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.
.PP
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 \s-1OK\s0 to include the \s-1POD\s0 documentation in with the module, but
\&\fIplease\fR write it all in one piece at the end of the file, \fIafter\fR the code
(just look at any other \f(CW\*(C`Template::*\*(C'\fR module for an example). It's a
religious issue, I know, but I have a strong distaste for \s-1POD\s0 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 \s-1HTML\s0).
.PP
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).
.PP
Please also make sure you add your name to the lib/Template/Manual/Credits.pod
file (if it isn't already there).
.PP
Then commit your changes and send a pull request.

Zerion Mini Shell 1.0