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   insert($template)
347       This method returns the source content of a template file without
348       performing any evaluation.  It is used to implement the "INSERT"
349       directive.
350
351   throw($error_type, $error_message, \$output)
352       Raises an exception in the form of a Template::Exception object by
353       calling "die()". This method may be passed a reference to an existing
354       Template::Exception object; a single value containing an error message
355       which is used to instantiate a Template::Exception of type '"undef"';
356       or a pair of values representing the exception "type" and "info" from
357       which a Template::Exception object is instantiated. e.g.
358
359           $context->throw($exception);
360           $context->throw("I'm sorry Dave, I can't do that");
361           $context->throw('denied', "I'm sorry Dave, I can't do that");
362
363       The optional third parameter may be a reference to the current output
364       buffer.  This is then stored in the exception object when created,
365       allowing the catcher to examine and use the output up to the point at
366       which the exception was raised.
367
368           $output .= 'blah blah blah';
369           $output .= 'more rhubarb';
370           $context->throw('yack', 'Too much yacking', \$output);
371
372   catch($exception, \$output)
373       Catches an exception thrown, either as a reference to a
374       Template::Exception object or some other value. In the latter case, the
375       error string is promoted to a Template::Exception object of '"undef"'
376       type. This method also accepts a reference to the current output buffer
377       which is passed to the Template::Exception constructor, or is appended
378       to the output buffer stored in an existing Template::Exception object,
379       if unique (i.e. not the same reference). By this process, the correct
380       state of the output buffer can be reconstructed for simple or nested
381       throws.
382
383   define_block($name, $block)
384       Adds a new block definition to the internal BLOCKS cache.  The first
385       argument should contain the name of the block and the second a
386       reference to a Template::Document object or template sub-routine, or
387       template text which is automatically compiled into a template sub-
388       routine.
389
390       Returns a true value (the sub-routine or Template::Document reference)
391       on success or undef on failure. The relevant error message can be
392       retrieved by calling the error() method.
393
394   define_filter($name, \&filter, $is_dynamic)
395       Adds a new filter definition by calling the store() method on each of
396       the LOAD_FILTERS providers until accepted (in the usual case, this is
397       accepted straight away by the one and only Template::Filters provider).
398       The first argument should contain the name of the filter and the second
399       a reference to a filter subroutine. The optional third argument can be
400       set to any true value to indicate that the subroutine is a dynamic
401       filter factory.
402
403       Returns a true value or throws a '"filter"' exception on error.
404
405   define_vmethod($type, $name, $code)
406       This method is a wrapper around the Template::Stash define_vmethod()
407       method.  It can be used to define new virtual methods.
408
409           # define a new scalar (item) virtual method
410           $context->define_vmethod(
411               item => ucfirst => sub {
412                   my $text = shift;
413                   return ucfirst $text;
414               }
415           )
416
417   define_view($name, \%params)
418       This method allows you to define a named view.
419
420           $context->define_view(
421               my_view => {
422                   prefix => 'my_templates/'
423               }
424           );
425
426       The view is then accessible as a template variable.
427
428           [% my_view.print(some_data) %]
429
430   define_views($views)
431       This method allows you to define multiple named views.  A reference to
432       a hash array or list reference should be passed as an argument.
433
434           $context->define_view({     # hash reference
435               my_view_one => {
436                   prefix => 'my_templates_one/'
437               },
438               my_view_two => {
439                   prefix => 'my_templates_two/'
440               }
441           });
442
443       If you're defining multiple views of which one or more are based on
444       other views in the same definition then you should pass them as a list
445       reference.  This ensures that they get created in the right order (Perl
446       does not preserve the order of items defined in a hash reference so you
447       can't guarantee that your base class view will be defined before your
448       subclass view).
449
450           $context->define_view([     # list referenence
451               my_view_one => {
452                   prefix => 'my_templates_one/'
453               },
454               my_view_two => {
455                   prefix => 'my_templates_two/' ,
456                   base   => 'my_view_one',
457               }
458           ]);
459
460       The views are then accessible as template variables.
461
462           [% my_view_one.print(some_data) %]
463           [% my_view_two.print(some_data) %]
464
465       See also the VIEWS option.
466
467   stash()
468       This method returns the Template::Stash object used internally to
469       manage template variables.
470
471   localise(\%vars)
472       Clones the stash to create a context with localised variables.  Returns
473       a reference to the newly cloned stash object which is also stored
474       internally.
475
476           $stash = $context->localise();
477
478   delocalise()
479       Restore the stash to its state prior to localisation.
480
481           $stash = $context->delocalise();
482
483   visit(\%blocks)
484       This method is called by Template::Document objects immediately before
485       they process their content.  It is called to register any local "BLOCK"
486       definitions with the context object so that they may be subsequently
487       delivered on request.
488
489   leave()
490       Compliment to the visit() method. Called by Template::Document objects
491       immediately after they process their content.
492
493   view()
494       This method creates a Template::View object bound to the context.
495
496   reset()
497       Clears the local BLOCKS cache of any "BLOCK" definitions.  Any initial
498       set of BLOCKS specified as a configuration item to the constructor will
499       be reinstated.
500
501   debugging($flag, @args)
502       This method is used to control debugging output.  It is used to
503       implement the DEBUG directive.
504
505       The first argument can be "on" or "off" to enable or disable debugging
506       respectively.  The numerical values 0 and 1 can also be used if you
507       prefer.
508
509           $context->debugging('on');
510
511       Alternately, the first argument can be "format" to define a new debug
512       message format.  The second argument should be the format string which
513       can contain any of the $file, $line or $text symbols to indicate where
514       the relevant values should be inserted.
515
516           # note single quotes to prevent interpolated of variables
517           $context->debugging( format => '## $file line $line: $text' );
518
519       The final use of this method is to generate debugging messages
520       themselves.  The first argument should be "msg", followed by a
521       reference to a hash array of value to insert into the debugging format
522       string.
523
524           $context->debugging(
525               msg => {
526                   line => 20,
527                   file => 'example.tt',
528                   text => 'Trampoline! Trampoline!',
529               }
530           );
531
532   AUTOLOAD
533       An "AUTOLOAD" method provides access to context configuration items.
534
535           $stash     = $context->stash();
536           $tflag     = $context->trim();
537           $epflag    = $context->eval_perl();
538           ...
539

AUTHOR

541       Andy Wardley <abw@wardley.org> <http://wardley.org/>
542
544       Copyright (C) 1996-2013 Andy Wardley.  All Rights Reserved.
545
546       This module is free software; you can redistribute it and/or modify it
547       under the same terms as Perl itself.
548

SEE ALSO

550       Template, Template::Document, Template::Exception, Template::Filters,
551       Template::Plugins, Template::Provider, Template::Service,
552       Template::Stash
553
554
555
556perl v5.28.1                      2018-10-11              Template::Context(3)
Impressum