1Template::Context(3)  User Contributed Perl Documentation Template::Context(3)
2
3
4

NAME

6       Template::Context - Runtime context in which templates are processed
7

SYNOPSIS

9           use Template::Context;
10
11           # constructor
12           $context = Template::Context->new(\%config)
13               || die $Template::Context::ERROR;
14
15           # fetch (load and compile) a template
16           $template = $context->template($template_name);
17
18           # fetch (load and instantiate) a plugin object
19           $plugin = $context->plugin($name, \@args);
20
21           # fetch (return or create) a filter subroutine
22           $filter = $context->filter($name, \@args, $alias);
23
24           # process/include a template, errors are thrown via die()
25           $output = $context->process($template, \%vars);
26           $output = $context->include($template, \%vars);
27
28           # raise an exception via die()
29           $context->throw($error_type, $error_message, \$output_buffer);
30
31           # catch an exception, clean it up and fix output buffer
32           $exception = $context->catch($exception, \$output_buffer);
33
34           # save/restore the stash to effect variable localisation
35           $new_stash = $context->localise(\%vars);
36           $old_stash = $context->delocalise();
37
38           # add new BLOCK or FILTER definitions
39           $context->define_block($name, $block);
40           $context->define_filter($name, \&filtersub, $is_dynamic);
41
42           # reset context, clearing any imported BLOCK definitions
43           $context->reset();
44
45           # methods for accessing internal items
46           $stash     = $context->stash();
47           $tflag     = $context->trim();
48           $epflag    = $context->eval_perl();
49           $providers = $context->templates();
50           $providers = $context->plugins();
51           $providers = $context->filters();
52           ...
53

DESCRIPTION

55       The "Template::Context" module defines an object class for representing
56       a runtime context in which templates are processed.  It provides an
57       interface to the fundamental operations of the Template Toolkit
58       processing engine through which compiled templates (i.e. Perl code
59       constructed from the template source) can process templates, load
60       plugins and filters, raise exceptions and so on.
61
62       A default "Template::Context" object is created by the Template module.
63       Any "Template::Context" options may be passed to the Template new()
64       constructor method and will be forwarded to the "Template::Context"
65       constructor.
66
67           use Template;
68
69           my $template = Template->new({
70               TRIM      => 1,
71               EVAL_PERL => 1,
72               BLOCKS    => {
73                   header => 'This is the header',
74                   footer => 'This is the footer',
75               },
76           });
77
78       Similarly, the "Template::Context" constructor will forward all
79       configuration parameters onto other default objects (e.g.
80       Template::Provider, Template::Plugins, Template::Filters, etc.) that it
81       may need to instantiate.
82
83           $context = Template::Context->new({
84               INCLUDE_PATH => '/home/abw/templates', # provider option
85               TAG_STYLE    => 'html',                # parser option
86           });
87
88       A "Template::Context" object (or subclass) can be explicitly
89       instantiated and passed to the Template new() constructor method as the
90       "CONTEXT" configuration item.
91
92           use Template;
93           use Template::Context;
94
95           my $context  = Template::Context->new({ TRIM => 1 });
96           my $template = Template->new({ CONTEXT => $context });
97
98       The Template module uses the Template::Config context() factory method
99       to create a default context object when required. The
100       $Template::Config::CONTEXT package variable may be set to specify an
101       alternate context module. This will be loaded automatically and its
102       new() constructor method called by the context() factory method when a
103       default context object is required.
104
105           use Template;
106
107           $Template::Config::CONTEXT = 'MyOrg::Template::Context';
108
109           my $template = Template->new({
110               EVAL_PERL   => 1,
111               EXTRA_MAGIC => 'red hot',  # your extra config items
112               ...
113           });
114

METHODS

116   new(\%params)
117       The "new()" constructor method is called to instantiate a
118       "Template::Context" object. Configuration parameters may be specified
119       as a HASH reference or as a list of "name => value" pairs.
120
121           my $context = Template::Context->new({
122               INCLUDE_PATH => 'header',
123               POST_PROCESS => 'footer',
124           });
125
126           my $context = Template::Context->new( EVAL_PERL => 1 );
127
128       The "new()" method returns a "Template::Context" object or "undef" on
129       error. In the latter case, a relevant error message can be retrieved by
130       the error() class method or directly from the $Template::Context::ERROR
131       package variable.
132
133           my $context = Template::Context->new(\%config)
134               || die Template::Context->error();
135
136           my $context = Template::Context->new(\%config)
137               || die $Template::Context::ERROR;
138
139       The following configuration items may be specified.  Please see
140       Template::Manual::Config for further details.
141
142       VARIABLES
143
144       The VARIABLES option can be used to specify a hash array of template
145       variables.
146
147           my $context = Template::Context->new({
148               VARIABLES => {
149                   title   => 'A Demo Page',
150                   author  => 'Joe Random Hacker',
151                   version => 3.14,
152               },
153           };
154
155       BLOCKS
156
157       The BLOCKS option can be used to pre-define a default set of template
158       blocks.
159
160           my $context = Template::Context->new({
161               BLOCKS => {
162                   header  => 'The Header.  [% title %]',
163                   footer  => sub { return $some_output_text },
164                   another => Template::Document->new({ ... }),
165               },
166           });
167
168       VIEWS
169
170       The VIEWS option can be used to pre-define one or more Template::View
171       objects.
172
173           my $context = Template::Context->new({
174               VIEWS => [
175                   bottom => { prefix => 'bottom/' },
176                   middle => { prefix => 'middle/', base => 'bottom' },
177                   top    => { prefix => 'top/',    base => 'middle' },
178               ],
179           });
180
181       TRIM
182
183       The TRIM option can be set to have any leading and trailing whitespace
184       automatically removed from the output of all template files and
185       "BLOCK"s.
186
187       example:
188
189           [% BLOCK foo %]
190
191           Line 1 of foo
192
193           [% END %]
194
195           before
196           [% INCLUDE foo %]
197           after
198
199       output:
200
201           before
202           Line 1 of foo
203           after
204
205       EVAL_PERL
206
207       The EVAL_PERL is used to indicate if "PERL" and/or "RAWPERL" blocks
208       should be evaluated. It is disabled by default.
209
210       RECURSION
211
212       The RECURSION can be set to allow templates to recursively process
213       themselves, either directly (e.g. template "foo" calls "INCLUDE foo")
214       or indirectly (e.g.  "foo" calls "INCLUDE bar" which calls "INCLUDE
215       foo").
216
217       LOAD_TEMPLATES
218
219       The LOAD_TEMPLATES option can be used to provide a reference to a list
220       of Template::Provider objects or sub-classes thereof which will take
221       responsibility for loading and compiling templates.
222
223           my $context = Template::Context->new({
224               LOAD_TEMPLATES => [
225                   MyOrg::Template::Provider->new({ ... }),
226                   Template::Provider->new({ ... }),
227               ],
228           });
229
230       LOAD_PLUGINS
231
232       The LOAD_PLUGINS options can be used to specify a list of provider
233       objects responsible for loading and instantiating template plugin
234       objects.
235
236           my $context = Template::Context->new({
237               LOAD_PLUGINS => [
238                   MyOrg::Template::Plugins->new({ ... }),
239                   Template::Plugins->new({ ... }),
240               ],
241           });
242
243       LOAD_FILTERS
244
245       The LOAD_FILTERS option can be used to specify a list of provider
246       objects for returning and/or creating filter subroutines.
247
248           my $context = Template::Context->new({
249               LOAD_FILTERS => [
250                   MyTemplate::Filters->new(),
251                   Template::Filters->new(),
252               ],
253           });
254
255       STASH
256
257       The STASH option can be used to specify a Template::Stash object or
258       sub-class which will take responsibility for managing template
259       variables.
260
261           my $stash = MyOrg::Template::Stash->new({ ... });
262           my $context = Template::Context->new({
263               STASH => $stash,
264           });
265
266       DEBUG
267
268       The DEBUG option can be used to enable various debugging features of
269       the Template::Context module.
270
271           use Template::Constants qw( :debug );
272
273           my $template = Template->new({
274               DEBUG => DEBUG_CONTEXT | DEBUG_DIRS,
275           });
276
277   template($name)
278       Returns a compiled template by querying each of the LOAD_TEMPLATES
279       providers (instances of Template::Provider, or sub-class) in turn.
280
281           $template = $context->template('header');
282
283       On error, a Template::Exception object of type '"file"' is thrown via
284       "die()".  This can be caught by enclosing the call to "template()" in
285       an "eval" block and examining $@.
286
287           eval { $template = $context->template('header') };
288           if ($@) {
289               print "failed to fetch template: $@\n";
290           }
291
292   plugin($name, \@args)
293       Instantiates a plugin object by querying each of the LOAD_PLUGINS
294       providers. The default LOAD_PLUGINS provider is a Template::Plugins
295       object which attempts to load plugin modules, according the various
296       configuration items such as PLUGIN_BASE, LOAD_PERL, etc., and then
297       instantiate an object via new(). A reference to a list of constructor
298       arguments may be passed as the second parameter. These are forwarded to
299       the plugin constructor.
300
301       Returns a reference to a plugin (which is generally an object, but
302       doesn't have to be).  Errors are thrown as Template::Exception objects
303       with the type set to '"plugin"'.
304
305           $plugin = $context->plugin('DBI', 'dbi:msql:mydbname');
306
307   filter($name, \@args, $alias)
308       Instantiates a filter subroutine by querying the LOAD_FILTERS
309       providers.  The default LOAD_FILTERS provider is a Template::Filters
310       object.
311
312       Additional arguments may be passed by list reference along with an
313       optional alias under which the filter will be cached for subsequent
314       use. The filter is cached under its own $name if $alias is undefined.
315       Subsequent calls to "filter($name)" will return the cached entry, if
316       defined. Specifying arguments bypasses the caching mechanism and always
317       creates a new filter. Errors are thrown as Template::Exception objects
318       with the type set to '"filter"'.
319
320           # static filter (no args)
321           $filter = $context->filter('html');
322
323           # dynamic filter (args) aliased to 'padright'
324           $filter = $context->filter('format', '%60s', 'padright');
325
326           # retrieve previous filter via 'padright' alias
327           $filter = $context->filter('padright');
328
329   process($template, \%vars)
330       Processes a template named or referenced by the first parameter and
331       returns the output generated.  An optional reference to a hash array
332       may be passed as the second parameter, containing variable definitions
333       which will be set before the template is processed.  The template is
334       processed in the current context, with no localisation of variables
335       performed.   Errors are thrown as Template::Exception objects via
336       "die()".
337
338           $output = $context->process('header', { title => 'Hello World' });
339
340   include($template, \%vars)
341       Similar to process(), but using localised variables.  Changes made to
342       any variables will only persist until the "include()" method completes.
343
344           $output = $context->include('header', { title => 'Hello World' });
345
346   throw($error_type, $error_message, \$output)
347       Raises an exception in the form of a Template::Exception object by
348       calling "die()". This method may be passed a reference to an existing
349       Template::Exception object; a single value containing an error message
350       which is used to instantiate a Template::Exception of type '"undef"';
351       or a pair of values representing the exception "type" and "info" from
352       which a Template::Exception object is instantiated. e.g.
353
354           $context->throw($exception);
355           $context->throw("I'm sorry Dave, I can't do that");
356           $context->throw('denied', "I'm sorry Dave, I can't do that");
357
358       The optional third parameter may be a reference to the current output
359       buffer.  This is then stored in the exception object when created,
360       allowing the catcher to examine and use the output up to the point at
361       which the exception was raised.
362
363           $output .= 'blah blah blah';
364           $output .= 'more rhubarb';
365           $context->throw('yack', 'Too much yacking', \$output);
366
367   catch($exception, \$output)
368       Catches an exception thrown, either as a reference to a
369       Template::Exception object or some other value. In the latter case, the
370       error string is promoted to a Template::Exception object of '"undef"'
371       type. This method also accepts a reference to the current output buffer
372       which is passed to the Template::Exception constructor, or is appended
373       to the output buffer stored in an existing Template::Exception object,
374       if unique (i.e. not the same reference). By this process, the correct
375       state of the output buffer can be reconstructed for simple or nested
376       throws.
377
378   define_block($name, $block)
379       Adds a new block definition to the internal BLOCKS cache.  The first
380       argument should contain the name of the block and the second a
381       reference to a Template::Document object or template sub-routine, or
382       template text which is automatically compiled into a template sub-
383       routine.
384
385       Returns a true value (the sub-routine or Template::Document reference)
386       on success or undef on failure. The relevant error message can be
387       retrieved by calling the error() method.
388
389   define_filter($name, \&filter, $is_dynamic)
390       Adds a new filter definition by calling the store() method on each of
391       the LOAD_FILTERS providers until accepted (in the usual case, this is
392       accepted straight away by the one and only Template::Filters provider).
393       The first argument should contain the name of the filter and the second
394       a reference to a filter subroutine. The optional third argument can be
395       set to any true value to indicate that the subroutine is a dynamic
396       filter factory.
397
398       Returns a true value or throws a '"filter"' exception on error.
399
400   define_view($name, \%params)
401       This method allows you to define a named view.
402
403           $context->define_view(
404               my_view => {
405                   prefix => 'my_templates/'
406               }
407           );
408
409       The view is then accessible as a template variable.
410
411           [% my_view.print(some_data) %]
412
413   define_views($views)
414       This method allows you to define multiple named views.  A reference to
415       a hash array or list reference should be passed as an argument.
416
417           $context->define_view({     # hash reference
418               my_view_one => {
419                   prefix => 'my_templates_one/'
420               },
421               my_view_two => {
422                   prefix => 'my_templates_two/'
423               }
424           });
425
426       If you're defining multiple views of which one or more are based on
427       other views in the same definition then you should pass them as a list
428       reference.  This ensures that they get created in the right order (Perl
429       does not preserve the order of items defined in a hash reference so you
430       can't guarantee that your base class view will be defined before your
431       subclass view).
432
433           $context->define_view([     # list referenence
434               my_view_one => {
435                   prefix => 'my_templates_one/'
436               },
437               my_view_two => {
438                   prefix => 'my_templates_two/' ,
439                   base   => 'my_view_one',
440               }
441           ]);
442
443       The views are then accessible as template variables.
444
445           [% my_view_one.print(some_data) %]
446           [% my_view_two.print(some_data) %]
447
448       See also the VIEWS option.
449
450   localise(\%vars)
451       Clones the stash to create a context with localised variables.  Returns
452       a reference to the newly cloned stash object which is also stored
453       internally.
454
455           $stash = $context->localise();
456
457   delocalise()
458       Restore the stash to its state prior to localisation.
459
460           $stash = $context->delocalise();
461
462   visit(\%blocks)
463       This method is called by Template::Document objects immediately before
464       they process their content.  It is called to register any local "BLOCK"
465       definitions with the context object so that they may be subsequently
466       delivered on request.
467
468   leave()
469       Compliment to the visit() method. Called by Template::Document objects
470       immediately after they process their content.
471
472   reset()
473       Clears the local BLOCKS cache of any "BLOCK" definitions.  Any initial
474       set of BLOCKS specified as a configuration item to the constructor will
475       be reinstated.
476
477   AUTOLOAD
478       An "AUTOLOAD" method provides access to context configuration items.
479
480           $stash     = $context->stash();
481           $tflag     = $context->trim();
482           $epflag    = $context->eval_perl();
483           ...
484

AUTHOR

486       Andy Wardley <abw@wardley.org> <http://wardley.org/>
487
489       Copyright (C) 1996-2007 Andy Wardley.  All Rights Reserved.
490
491       This module is free software; you can redistribute it and/or modify it
492       under the same terms as Perl itself.
493

SEE ALSO

495       Template, Template::Document, Template::Exception, Template::Filters,
496       Template::Plugins, Template::Provider, Template::Service,
497       Template::Stash
498
499
500
501perl v5.10.1                      2009-05-20              Template::Context(3)
Impressum