1Template::Context(3) User Contributed Perl Documentation Template::Context(3)
2
3
4
6 Template::Context - Runtime context in which templates are processed
7
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
55 The Template::Context module defines an object class for representing a
56 runtime context in which templates are processed. It provides an
57 interface to the fundamental operations of the Template Toolkit pro‐
58 cessing engine through which compiled templates (i.e. Perl code con‐
59 structed from the template source) can process templates, load plugins
60 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() con‐
64 structor method and will be forwarded to the Template::Context con‐
65 structor.
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 configu‐
79 ration parameters onto other default objects (e.g. Template::Provider,
80 Template::Plugins, Template::Filters, etc.) that it may need to instan‐
81 tiate.
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/derivative) can be explicitly
89 instantiated and passed to the Template new() constructor method as the
90 CONTEXT 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 $Template::Con‐
100 fig::CONTEXT package variable may be set to specify an alternate con‐
101 text module. This will be loaded automatically and its new() construc‐
102 tor method called by the context() factory method when a default con‐
103 text 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
116 new(\%params)
117
118 The new() constructor method is called to instantiate a Template::Con‐
119 text object. Configuration parameters may be specified as a HASH ref‐
120 erence or as a list of (name => value) pairs.
121
122 my $context = Template::Context->new({
123 INCLUDE_PATH => 'header',
124 POST_PROCESS => 'footer',
125 });
126
127 my $context = Template::Context->new( EVAL_PERL => 1 );
128
129 The new() method returns a Template::Context object (or sub-class) or
130 undef on error. In the latter case, a relevant error message can be
131 retrieved by the error() class method or directly from the $Tem‐
132 plate::Context::ERROR package variable.
133
134 my $context = Template::Context->new(\%config)
135 ⎪⎪ die Template::Context->error();
136
137 my $context = Template::Context->new(\%config)
138 ⎪⎪ die $Template::Context::ERROR;
139
140 The following configuration items may be specified.
141
142 VARIABLES, PRE_DEFINE
143 The VARIABLES option (or PRE_DEFINE - they're equivalent) can be
144 used to specify a hash array of template variables that should be
145 used to pre-initialise the stash when it is created. These items
146 are ignored if the STASH item is defined.
147
148 my $context = Template::Context->new({
149 VARIABLES => {
150 title => 'A Demo Page',
151 author => 'Joe Random Hacker',
152 version => 3.14,
153 },
154 };
155
156 or
157
158 my $context = Template::Context->new({
159 PRE_DEFINE => {
160 title => 'A Demo Page',
161 author => 'Joe Random Hacker',
162 version => 3.14,
163 },
164 };
165
166 BLOCKS
167 The BLOCKS option can be used to pre-define a default set of tem‐
168 plate blocks. These should be specified as a reference to a hash
169 array mapping template names to template text, subroutines or Tem‐
170 plate::Document objects.
171
172 my $context = Template::Context->new({
173 BLOCKS => {
174 header => 'The Header. [% title %]',
175 footer => sub { return $some_output_text },
176 another => Template::Document->new({ ... }),
177 },
178 });
179
180 TRIM
181 The TRIM option can be set to have any leading and trailing white‐
182 space automatically removed from the output of all template files
183 and BLOCKs.
184
185 By example, the following BLOCK definition
186
187 [% BLOCK foo %]
188 Line 1 of foo
189 [% END %]
190
191 will be processed is as "\nLine 1 of foo\n". When INCLUDEd, the
192 surrounding newlines will also be introduced.
193
194 before
195 [% INCLUDE foo %]
196 after
197
198 output:
199 before
200
201 Line 1 of foo
202
203 after
204
205 With the TRIM option set to any true value, the leading and trail‐
206 ing newlines (which count as whitespace) will be removed from the
207 output of the BLOCK.
208
209 before
210 Line 1 of foo
211 after
212
213 The TRIM option is disabled (0) by default.
214
215 EVAL_PERL
216 This flag is used to indicate if PERL and/or RAWPERL blocks should
217 be evaluated. By default, it is disabled and any PERL or RAWPERL
218 blocks encountered will raise exceptions of type 'perl' with the
219 message 'EVAL_PERL not set'. Note however that any RAWPERL blocks
220 should always contain valid Perl code, regardless of the EVAL_PERL
221 flag. The parser will fail to compile templates that contain
222 invalid Perl code in RAWPERL blocks and will throw a 'file' excep‐
223 tion.
224
225 When using compiled templates (see COMPILE_EXT and COMPILE_DIR),
226 the EVAL_PERL has an affect when the template is compiled, and
227 again when the templates is subsequently processed, possibly in a
228 different context to the one that compiled it.
229
230 If the EVAL_PERL is set when a template is compiled, then all PERL
231 and RAWPERL blocks will be included in the compiled template. If
232 the EVAL_PERL option isn't set, then Perl code will be generated
233 which always throws a 'perl' exception with the message 'EVAL_PERL
234 not set' whenever the compiled template code is run.
235
236 Thus, you must have EVAL_PERL set if you want your compiled tem‐
237 plates to include PERL and RAWPERL blocks.
238
239 At some point in the future, using a different invocation of the
240 Template Toolkit, you may come to process such a pre-compiled tem‐
241 plate. Assuming the EVAL_PERL option was set at the time the tem‐
242 plate was compiled, then the output of any RAWPERL blocks will be
243 included in the compiled template and will get executed when the
244 template is processed. This will happen regardless of the runtime
245 EVAL_PERL status.
246
247 Regular PERL blocks are a little more cautious, however. If the
248 EVAL_PERL flag isn't set for the current context, that is, the one
249 which is trying to process it, then it will throw the familiar
250 'perl' exception with the message, 'EVAL_PERL not set'.
251
252 Thus you can compile templates to include PERL blocks, but option‐
253 ally disable them when you process them later. Note however that
254 it is possible for a PERL block to contain a Perl "BEGIN { # some
255 code }" block which will always get run regardless of the runtime
256 EVAL_PERL status. Thus, if you set EVAL_PERL when compiling tem‐
257 plates, it is assumed that you trust the templates to Do The Right
258 Thing. Otherwise you must accept the fact that there's no bullet‐
259 proof way to prevent any included code from trampling around in the
260 living room of the runtime environment, making a real nuisance of
261 itself if it really wants to. If you don't like the idea of such
262 uninvited guests causing a bother, then you can accept the default
263 and keep EVAL_PERL disabled.
264
265 RECURSION
266 The template processor will raise a file exception if it detects
267 direct or indirect recursion into a template. Setting this option
268 to any true value will allow templates to include each other recur‐
269 sively.
270
271 LOAD_TEMPLATES
272 The LOAD_TEMPLATE option can be used to provide a reference to a
273 list of Template::Provider objects or sub-classes thereof which
274 will take responsibility for loading and compiling templates.
275
276 my $context = Template::Context->new({
277 LOAD_TEMPLATES => [
278 MyOrg::Template::Provider->new({ ... }),
279 Template::Provider->new({ ... }),
280 ],
281 });
282
283 When a PROCESS, INCLUDE or WRAPPER directive is encountered, the
284 named template may refer to a locally defined BLOCK or a file rela‐
285 tive to the INCLUDE_PATH (or an absolute or relative path if the
286 appropriate ABSOLUTE or RELATIVE options are set). If a BLOCK def‐
287 inition can't be found (see the Template::Context template() method
288 for a discussion of BLOCK locality) then each of the LOAD_TEMPLATES
289 provider objects is queried in turn via the fetch() method to see
290 if it can supply the required template. Each provider can return a
291 compiled template, an error, or decline to service the request in
292 which case the responsibility is passed to the next provider. If
293 none of the providers can service the request then a 'not found'
294 error is returned. The same basic provider mechanism is also used
295 for the INSERT directive but it bypasses any BLOCK definitions and
296 doesn't attempt is to parse or process the contents of the template
297 file.
298
299 This is an implementation of the 'Chain of Responsibility' design
300 pattern as described in "Design Patterns", Erich Gamma, Richard
301 Helm, Ralph Johnson, John Vlissides), Addision-Wesley, ISBN
302 0-201-63361-2, page 223 .
303
304 If LOAD_TEMPLATES is undefined, a single default provider will be
305 instantiated using the current configuration parameters. For exam‐
306 ple, the Template::Provider INCLUDE_PATH option can be specified in
307 the Template::Context configuration and will be correctly passed to
308 the provider's constructor method.
309
310 my $context = Template::Context->new({
311 INCLUDE_PATH => '/here:/there',
312 });
313
314 LOAD_PLUGINS
315 The LOAD_PLUGINS options can be used to specify a list of provider
316 objects (i.e. they implement the fetch() method) which are respon‐
317 sible for loading and instantiating template plugin objects. The
318 Template::Content plugin() method queries each provider in turn in
319 a "Chain of Responsibility" as per the template() and filter()
320 methods.
321
322 my $context = Template::Context->new({
323 LOAD_PLUGINS => [
324 MyOrg::Template::Plugins->new({ ... }),
325 Template::Plugins->new({ ... }),
326 ],
327 });
328
329 By default, a single Template::Plugins object is created using the
330 current configuration hash. Configuration items destined for the
331 Template::Plugins constructor may be added to the Template::Context
332 constructor.
333
334 my $context = Template::Context->new({
335 PLUGIN_BASE => 'MyOrg::Template::Plugins',
336 LOAD_PERL => 1,
337 });
338
339 LOAD_FILTERS
340 The LOAD_FILTERS option can be used to specify a list of provider
341 objects (i.e. they implement the fetch() method) which are respon‐
342 sible for returning and/or creating filter subroutines. The Tem‐
343 plate::Context filter() method queries each provider in turn in a
344 "Chain of Responsibility" as per the template() and plugin() meth‐
345 ods.
346
347 my $context = Template::Context->new({
348 LOAD_FILTERS => [
349 MyTemplate::Filters->new(),
350 Template::Filters->new(),
351 ],
352 });
353
354 By default, a single Template::Filters object is created for the
355 LOAD_FILTERS list.
356
357 STASH
358 A reference to a Template::Stash object or sub-class which will
359 take responsibility for managing template variables.
360
361 my $stash = MyOrg::Template::Stash->new({ ... });
362 my $context = Template::Context->new({
363 STASH => $stash,
364 });
365
366 If unspecified, a default stash object is created using the VARI‐
367 ABLES configuration item to initialise the stash variables. These
368 may also be specified as the PRE_DEFINE option for backwards com‐
369 patibility with version 1.
370
371 my $context = Template::Context->new({
372 VARIABLES => {
373 id => 'abw',
374 name => 'Andy Wardley',
375 },
376 };
377
378 DEBUG
379 The DEBUG option can be used to enable various debugging features
380 of the Template::Context module.
381
382 use Template::Constants qw( :debug );
383
384 my $template = Template->new({
385 DEBUG => DEBUG_CONTEXT ⎪ DEBUG_DIRS,
386 });
387
388 The DEBUG value can include any of the following. Multiple values
389 should be combined using the logical OR operator, '⎪'.
390
391 DEBUG_CONTEXT
392 Enables general debugging messages for the Template::Context
393 module.
394
395 DEBUG_DIRS
396 This option causes the Template Toolkit to generate comments
397 indicating the source file, line and original text of each
398 directive in the template. These comments are embedded in the
399 template output using the format defined in the DEBUG_FORMAT
400 configuration item, or a simple default format if unspecified.
401
402 For example, the following template fragment:
403
404 Hello World
405
406 would generate this output:
407
408 ## input text line 1 : ##
409 Hello
410 ## input text line 2 : World ##
411 World
412
413 template($name)
414
415 Returns a compiled template by querying each of the LOAD_TEMPLATES
416 providers (instances of Template::Provider, or sub-class) in turn.
417
418 $template = $context->template('header');
419
420 On error, a Template::Exception object of type 'file' is thrown via
421 die(). This can be caught by enclosing the call to template() in an
422 eval block and examining $@.
423
424 eval {
425 $template = $context->template('header');
426 };
427 if ($@) {
428 print "failed to fetch template: $@\n";
429 }
430
431 plugin($name, \@args)
432
433 Instantiates a plugin object by querying each of the LOAD_PLUGINS
434 providers. The default LOAD_PLUGINS provider is a Template::Plugins
435 object which attempts to load plugin modules, according the various
436 configuration items such as PLUGIN_BASE, LOAD_PERL, etc., and then
437 instantiate an object via new(). A reference to a list of constructor
438 arguments may be passed as the second parameter. These are forwarded
439 to the plugin constructor.
440
441 Returns a reference to a plugin (which is generally an object, but
442 doesn't have to be). Errors are thrown as Template::Exception objects
443 of type 'plugin'.
444
445 $plugin = $context->plugin('DBI', 'dbi:msql:mydbname');
446
447 filter($name, \@args, $alias)
448
449 Instantiates a filter subroutine by querying the LOAD_FILTERS
450 providers. The default LOAD_FILTERS providers is a Template::Filters
451 object. Additional arguments may be passed by list reference along
452 with an optional alias under which the filter will be cached for subse‐
453 quent use. The filter is cached under its own $name if $alias is unde‐
454 fined. Subsequent calls to filter($name) will return the cached entry,
455 if defined. Specifying arguments bypasses the caching mechanism and
456 always creates a new filter. Errors are thrown as Template::Exception
457 objects of typre 'filter'.
458
459 # static filter (no args)
460 $filter = $context->filter('html');
461
462 # dynamic filter (args) aliased to 'padright'
463 $filter = $context->filter('format', '%60s', 'padright');
464
465 # retrieve previous filter via 'padright' alias
466 $filter = $context->filter('padright');
467
468 process($template, \%vars)
469
470 Processes a template named or referenced by the first parameter and
471 returns the output generated. An optional reference to a hash array
472 may be passed as the second parameter, containing variable definitions
473 which will be set before the template is processed. The template is
474 processed in the current context, with no localisation of variables
475 performed. Errors are thrown as Template::Exception objects via
476 die().
477
478 $output = $context->process('header', { title => 'Hello World' });
479
480 include($template, \%vars)
481
482 Similar to process() above, but using localised variables. Changes
483 made to any variables will only persist until the include() method com‐
484 pletes.
485
486 $output = $context->include('header', { title => 'Hello World' });
487
488 throw($error_type, $error_message, \$output)
489
490 Raises an exception in the form of a Template::Exception object by
491 calling die(). This method may be passed a reference to an existing
492 Template::Exception object; a single value containing an error message
493 which is used to instantiate a Template::Exception of type 'undef'; or
494 a pair of values representing the exception type and info from which a
495 Template::Exception object is instantiated. e.g.
496
497 $context->throw($exception);
498 $context->throw("I'm sorry Dave, I can't do that");
499 $context->throw('denied', "I'm sorry Dave, I can't do that");
500
501 The optional third parameter may be a reference to the current output
502 buffer. This is then stored in the exception object when created,
503 allowing the catcher to examine and use the output up to the point at
504 which the exception was raised.
505
506 $output .= 'blah blah blah';
507 $output .= 'more rhubarb';
508 $context->throw('yack', 'Too much yacking', \$output);
509
510 catch($exception, \$output)
511
512 Catches an exception thrown, either as a reference to a Tem‐
513 plate::Exception object or some other value. In the latter case, the
514 error string is promoted to a Template::Exception object of 'undef'
515 type. This method also accepts a reference to the current output buf‐
516 fer which is passed to the Template::Exception constructor, or is
517 appended to the output buffer stored in an existing Template::Exception
518 object, if unique (i.e. not the same reference). By this process, the
519 correct state of the output buffer can be reconstructed for simple or
520 nested throws.
521
522 define_block($name, $block)
523
524 Adds a new block definition to the internal BLOCKS cache. The first
525 argument should contain the name of the block and the second a refer‐
526 ence to a Template::Document object or template sub-routine, or tem‐
527 plate text which is automatically compiled into a template sub-routine.
528 Returns a true value (the sub-routine or Template::Document reference)
529 on success or undef on failure. The relevant error message can be
530 retrieved by calling the error() method.
531
532 define_filter($name, \&filter, $is_dynamic)
533
534 Adds a new filter definition by calling the store() method on each of
535 the LOAD_FILTERS providers until accepted (in the usual case, this is
536 accepted straight away by the one and only Template::Filters provider).
537 The first argument should contain the name of the filter and the second
538 a reference to a filter subroutine. The optional third argument can be
539 set to any true value to indicate that the subroutine is a dynamic fil‐
540 ter factory. Returns a true value or throws a 'filter' exception on
541 error.
542
543 localise(\%vars)
544
545 Clones the stash to create a context with localised variables. Returns
546 a reference to the newly cloned stash object which is also stored
547 internally.
548
549 $stash = $context->localise();
550
551 delocalise()
552
553 Restore the stash to its state prior to localisation.
554
555 $stash = $context->delocalise();
556
557 visit(\%blocks)
558
559 This method is called by Template::Document objects immediately before
560 they process their content. It is called to register any local BLOCK
561 definitions with the context object so that they may be subsequently
562 delivered on request.
563
564 leave()
565
566 Compliment to visit(), above. Called by Template::Document objects
567 immediately after they process their content.
568
569 reset()
570
571 Clears the local BLOCKS cache of any BLOCK definitions. Any initial
572 set of BLOCKS specified as a configuration item to the constructor will
573 be reinstated.
574
575 AUTOLOAD
576
577 An AUTOLOAD method provides access to context configuration items.
578
579 $stash = $context->stash();
580 $tflag = $context->trim();
581 $epflag = $context->eval_perl();
582 ...
583
585 Andy Wardley <abw@wardley.org>
586
587 <http://wardley.org/⎪http://wardley.org/>
588
590 2.98, distributed as part of the Template Toolkit version 2.18,
591 released on 09 February 2007.
592
594 Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
595
596 This module is free software; you can redistribute it and/or modify it
597 under the same terms as Perl itself.
598
600 Template, Template::Document, Template::Exception, Template::Filters,
601 Template::Plugins, Template::Provider, Template::Service, Tem‐
602 plate::Stash
603
604
605
606perl v5.8.8 2007-02-09 Template::Context(3)