| 1 |
#============================================================= -*-Perl-*- |
| 2 |
# |
| 3 |
# Template::Context |
| 4 |
# |
| 5 |
# DESCRIPTION |
| 6 |
# Module defining a context in which a template document is processed. |
| 7 |
# This is the runtime processing interface through which templates |
| 8 |
# can access the functionality of the Template Toolkit. |
| 9 |
# |
| 10 |
# AUTHOR |
| 11 |
# Andy Wardley <[email protected]> |
| 12 |
# |
| 13 |
# COPYRIGHT |
| 14 |
# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved. |
| 15 |
# |
| 16 |
# This module is free software; you can redistribute it and/or |
| 17 |
# modify it under the same terms as Perl itself. |
| 18 |
# |
| 19 |
#============================================================================ |
| 20 |
|
| 21 |
package Template::Context; |
| 22 |
|
| 23 |
use strict; |
| 24 |
use warnings; |
| 25 |
use base 'Template::Base'; |
| 26 |
|
| 27 |
use Template::Base; |
| 28 |
use Template::Config; |
| 29 |
use Template::Constants; |
| 30 |
use Template::Exception; |
| 31 |
use Scalar::Util 'blessed'; |
| 32 |
|
| 33 |
use constant DOCUMENT => 'Template::Document'; |
| 34 |
use constant EXCEPTION => 'Template::Exception'; |
| 35 |
use constant BADGER_EXCEPTION => 'Badger::Exception'; |
| 36 |
|
| 37 |
our $VERSION = 2.98; |
| 38 |
our $DEBUG = 0 unless defined $DEBUG; |
| 39 |
our $DEBUG_FORMAT = "\n## \$file line \$line : [% \$text %] ##\n"; |
| 40 |
our $VIEW_CLASS = 'Template::View'; |
| 41 |
our $AUTOLOAD; |
| 42 |
|
| 43 |
#======================================================================== |
| 44 |
# ----- PUBLIC METHODS ----- |
| 45 |
#======================================================================== |
| 46 |
|
| 47 |
#------------------------------------------------------------------------ |
| 48 |
# template($name) |
| 49 |
# |
| 50 |
# General purpose method to fetch a template and return it in compiled |
| 51 |
# form. In the usual case, the $name parameter will be a simple string |
| 52 |
# containing the name of a template (e.g. 'header'). It may also be |
| 53 |
# a reference to Template::Document object (or sub-class) or a Perl |
| 54 |
# sub-routine. These are considered to be compiled templates and are |
| 55 |
# returned intact. Finally, it may be a reference to any other kind |
| 56 |
# of valid input source accepted by Template::Provider (e.g. scalar |
| 57 |
# ref, glob, IO handle, etc). |
| 58 |
# |
| 59 |
# Templates may be cached at one of 3 different levels. The internal |
| 60 |
# BLOCKS member is a local cache which holds references to all |
| 61 |
# template blocks used or imported via PROCESS since the context's |
| 62 |
# reset() method was last called. This is checked first and if the |
| 63 |
# template is not found, the method then walks down the BLOCKSTACK |
| 64 |
# list. This contains references to the block definition tables in |
| 65 |
# any enclosing Template::Documents that we're visiting (e.g. we've |
| 66 |
# been called via an INCLUDE and we want to access a BLOCK defined in |
| 67 |
# the template that INCLUDE'd us). If nothing is defined, then we |
| 68 |
# iterate through the LOAD_TEMPLATES providers list as a 'chain of |
| 69 |
# responsibility' (see Design Patterns) asking each object to fetch() |
| 70 |
# the template if it can. |
| 71 |
# |
| 72 |
# Returns the compiled template. On error, undef is returned and |
| 73 |
# the internal ERROR value (read via error()) is set to contain an |
| 74 |
# error message of the form "$name: $error". |
| 75 |
#------------------------------------------------------------------------ |
| 76 |
|
| 77 |
sub template { |
| 78 |
my ($self, $name) = @_; |
| 79 |
my ($prefix, $blocks, $defblocks, $provider, $template, $error); |
| 80 |
my ($shortname, $blockname, $providers); |
| 81 |
|
| 82 |
$self->debug("template($name)") if $self->{ DEBUG }; |
| 83 |
|
| 84 |
# references to Template::Document (or sub-class) objects objects, or |
| 85 |
# CODE references are assumed to be pre-compiled templates and are |
| 86 |
# returned intact |
| 87 |
return $name |
| 88 |
if (blessed($name) && $name->isa(DOCUMENT)) |
| 89 |
|| ref($name) eq 'CODE'; |
| 90 |
|
| 91 |
$shortname = $name; |
| 92 |
|
| 93 |
unless (ref $name) { |
| 94 |
|
| 95 |
$self->debug("looking for block [$name]") if $self->{ DEBUG }; |
| 96 |
|
| 97 |
# we first look in the BLOCKS hash for a BLOCK that may have |
| 98 |
# been imported from a template (via PROCESS) |
| 99 |
return $template |
| 100 |
if ($template = $self->{ BLOCKS }->{ $name }); |
| 101 |
|
| 102 |
# then we iterate through the BLKSTACK list to see if any of the |
| 103 |
# Template::Documents we're visiting define this BLOCK |
| 104 |
foreach $blocks (@{ $self->{ BLKSTACK } }) { |
| 105 |
return $template |
| 106 |
if $blocks && ($template = $blocks->{ $name }); |
| 107 |
} |
| 108 |
|
| 109 |
# now it's time to ask the providers, so we look to see if any |
| 110 |
# prefix is specified to indicate the desired provider set. |
| 111 |
if ($^O eq 'MSWin32') { |
| 112 |
# let C:/foo through |
| 113 |
$prefix = $1 if $shortname =~ s/^(\w{2,})://o; |
| 114 |
} |
| 115 |
else { |
| 116 |
$prefix = $1 if $shortname =~ s/^(\w+)://; |
| 117 |
} |
| 118 |
|
| 119 |
if (defined $prefix) { |
| 120 |
$providers = $self->{ PREFIX_MAP }->{ $prefix } |
| 121 |
|| return $self->throw( Template::Constants::ERROR_FILE, |
| 122 |
"no providers for template prefix '$prefix'"); |
| 123 |
} |
| 124 |
} |
| 125 |
$providers = $self->{ PREFIX_MAP }->{ default } |
| 126 |
|| $self->{ LOAD_TEMPLATES } |
| 127 |
unless $providers; |
| 128 |
|
| 129 |
|
| 130 |
# Finally we try the regular template providers which will |
| 131 |
# handle references to files, text, etc., as well as templates |
| 132 |
# reference by name. If |
| 133 |
|
| 134 |
$blockname = ''; |
| 135 |
while ($shortname) { |
| 136 |
$self->debug("asking providers for [$shortname] [$blockname]") |
| 137 |
if $self->{ DEBUG }; |
| 138 |
|
| 139 |
foreach my $provider (@$providers) { |
| 140 |
($template, $error) = $provider->fetch($shortname, $prefix); |
| 141 |
if ($error) { |
| 142 |
if ($error == Template::Constants::STATUS_ERROR) { |
| 143 |
# $template contains exception object |
| 144 |
if (blessed($template) && $template->isa(EXCEPTION) |
| 145 |
&& $template->type eq Template::Constants::ERROR_FILE) { |
| 146 |
$self->throw($template); |
| 147 |
} |
| 148 |
else { |
| 149 |
$self->throw( Template::Constants::ERROR_FILE, $template ); |
| 150 |
} |
| 151 |
} |
| 152 |
# DECLINE is ok, carry on |
| 153 |
} |
| 154 |
elsif (length $blockname) { |
| 155 |
return $template |
| 156 |
if $template = $template->blocks->{ $blockname }; |
| 157 |
} |
| 158 |
else { |
| 159 |
return $template; |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
last if ref $shortname || ! $self->{ EXPOSE_BLOCKS }; |
| 164 |
$shortname =~ s{/([^/]+)$}{} || last; |
| 165 |
$blockname = length $blockname ? "$1/$blockname" : $1; |
| 166 |
} |
| 167 |
|
| 168 |
$self->throw(Template::Constants::ERROR_FILE, "$name: not found"); |
| 169 |
} |
| 170 |
|
| 171 |
|
| 172 |
#------------------------------------------------------------------------ |
| 173 |
# plugin($name, \@args) |
| 174 |
# |
| 175 |
# Calls on each of the LOAD_PLUGINS providers in turn to fetch() (i.e. load |
| 176 |
# and instantiate) a plugin of the specified name. Additional parameters |
| 177 |
# passed are propagated to the new() constructor for the plugin. |
| 178 |
# Returns a reference to a new plugin object or other reference. On |
| 179 |
# error, undef is returned and the appropriate error message is set for |
| 180 |
# subsequent retrieval via error(). |
| 181 |
#------------------------------------------------------------------------ |
| 182 |
|
| 183 |
sub plugin { |
| 184 |
my ($self, $name, $args) = @_; |
| 185 |
my ($provider, $plugin, $error); |
| 186 |
|
| 187 |
$self->debug("plugin($name, ", defined $args ? @$args : '[ ]', ')') |
| 188 |
if $self->{ DEBUG }; |
| 189 |
|
| 190 |
# request the named plugin from each of the LOAD_PLUGINS providers in turn |
| 191 |
foreach my $provider (@{ $self->{ LOAD_PLUGINS } }) { |
| 192 |
($plugin, $error) = $provider->fetch($name, $args, $self); |
| 193 |
return $plugin unless $error; |
| 194 |
if ($error == Template::Constants::STATUS_ERROR) { |
| 195 |
$self->throw($plugin) if ref $plugin; |
| 196 |
$self->throw(Template::Constants::ERROR_PLUGIN, $plugin); |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
$self->throw(Template::Constants::ERROR_PLUGIN, "$name: plugin not found"); |
| 201 |
} |
| 202 |
|
| 203 |
|
| 204 |
#------------------------------------------------------------------------ |
| 205 |
# filter($name, \@args, $alias) |
| 206 |
# |
| 207 |
# Similar to plugin() above, but querying the LOAD_FILTERS providers to |
| 208 |
# return filter instances. An alias may be provided which is used to |
| 209 |
# save the returned filter in a local cache. |
| 210 |
#------------------------------------------------------------------------ |
| 211 |
|
| 212 |
sub filter { |
| 213 |
my ($self, $name, $args, $alias) = @_; |
| 214 |
my ($provider, $filter, $error); |
| 215 |
|
| 216 |
$self->debug("filter($name, ", |
| 217 |
defined $args ? @$args : '[ ]', |
| 218 |
defined $alias ? $alias : '<no alias>', ')') |
| 219 |
if $self->{ DEBUG }; |
| 220 |
|
| 221 |
# use any cached version of the filter if no params provided |
| 222 |
return $filter |
| 223 |
if ! $args && ! ref $name |
| 224 |
&& ($filter = $self->{ FILTER_CACHE }->{ $name }); |
| 225 |
|
| 226 |
# request the named filter from each of the FILTERS providers in turn |
| 227 |
foreach my $provider (@{ $self->{ LOAD_FILTERS } }) { |
| 228 |
($filter, $error) = $provider->fetch($name, $args, $self); |
| 229 |
last unless $error; |
| 230 |
if ($error == Template::Constants::STATUS_ERROR) { |
| 231 |
$self->throw($filter) if ref $filter; |
| 232 |
$self->throw(Template::Constants::ERROR_FILTER, $filter); |
| 233 |
} |
| 234 |
# return $self->error($filter) |
| 235 |
# if $error == &Template::Constants::STATUS_ERROR; |
| 236 |
} |
| 237 |
|
| 238 |
return $self->error("$name: filter not found") |
| 239 |
unless $filter; |
| 240 |
|
| 241 |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| 242 |
# commented out by abw on 19 Nov 2001 to fix problem with xmlstyle |
| 243 |
# plugin which may re-define a filter by calling define_filter() |
| 244 |
# multiple times. With the automatic aliasing/caching below, any |
| 245 |
# new filter definition isn't seen. Don't think this will cause |
| 246 |
# any problems as filters explicitly supplied with aliases will |
| 247 |
# still work as expected. |
| 248 |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| 249 |
# alias defaults to name if undefined |
| 250 |
# $alias = $name |
| 251 |
# unless defined($alias) or ref($name) or $args; |
| 252 |
|
| 253 |
# cache FILTER if alias is valid |
| 254 |
$self->{ FILTER_CACHE }->{ $alias } = $filter |
| 255 |
if $alias; |
| 256 |
|
| 257 |
return $filter; |
| 258 |
} |
| 259 |
|
| 260 |
|
| 261 |
#------------------------------------------------------------------------ |
| 262 |
# view(\%config) |
| 263 |
# |
| 264 |
# Create a new Template::View bound to this context. |
| 265 |
#------------------------------------------------------------------------ |
| 266 |
|
| 267 |
sub view { |
| 268 |
my $self = shift; |
| 269 |
require Template::View; |
| 270 |
return $VIEW_CLASS->new($self, @_) |
| 271 |
|| $self->throw(&Template::Constants::ERROR_VIEW, |
| 272 |
$VIEW_CLASS->error); |
| 273 |
} |
| 274 |
|
| 275 |
|
| 276 |
#------------------------------------------------------------------------ |
| 277 |
# process($template, \%params) [% PROCESS template var=val ... %] |
| 278 |
# process($template, \%params, $local) [% INCLUDE template var=val ... %] |
| 279 |
# |
| 280 |
# Processes the template named or referenced by the first parameter. |
| 281 |
# The optional second parameter may reference a hash array of variable |
| 282 |
# definitions. These are set before the template is processed by |
| 283 |
# calling update() on the stash. Note that, unless the third parameter |
| 284 |
# is true, the context is not localised and these, and any other |
| 285 |
# variables set in the template will retain their new values after this |
| 286 |
# method returns. The third parameter is in place so that this method |
| 287 |
# can handle INCLUDE calls: the stash will be localized. |
| 288 |
# |
| 289 |
# Returns the output of processing the template. Errors are thrown |
| 290 |
# as Template::Exception objects via die(). |
| 291 |
#------------------------------------------------------------------------ |
| 292 |
|
| 293 |
sub process { |
| 294 |
my ($self, $template, $params, $localize) = @_; |
| 295 |
my ($trim, $blocks) = @$self{ qw( TRIM BLOCKS ) }; |
| 296 |
my (@compiled, $name, $compiled); |
| 297 |
my ($stash, $component, $tblocks, $error, $tmpout); |
| 298 |
my $output = ''; |
| 299 |
|
| 300 |
$template = [ $template ] unless ref $template eq 'ARRAY'; |
| 301 |
|
| 302 |
$self->debug("process([ ", join(', '), @$template, ' ], ', |
| 303 |
defined $params ? $params : '<no params>', ', ', |
| 304 |
$localize ? '<localized>' : '<unlocalized>', ')') |
| 305 |
if $self->{ DEBUG }; |
| 306 |
|
| 307 |
# fetch compiled template for each name specified |
| 308 |
foreach $name (@$template) { |
| 309 |
push(@compiled, $self->template($name)); |
| 310 |
} |
| 311 |
|
| 312 |
if ($localize) { |
| 313 |
# localise the variable stash with any parameters passed |
| 314 |
$stash = $self->{ STASH } = $self->{ STASH }->clone($params); |
| 315 |
} else { |
| 316 |
# update stash with any new parameters passed |
| 317 |
$self->{ STASH }->update($params); |
| 318 |
$stash = $self->{ STASH }; |
| 319 |
} |
| 320 |
|
| 321 |
eval { |
| 322 |
# save current component |
| 323 |
eval { $component = $stash->get('component') }; |
| 324 |
|
| 325 |
foreach $name (@$template) { |
| 326 |
$compiled = shift @compiled; |
| 327 |
my $element = ref $compiled eq 'CODE' |
| 328 |
? { (name => (ref $name ? '' : $name), modtime => time()) } |
| 329 |
: $compiled; |
| 330 |
|
| 331 |
if (blessed($component) && $component->isa(DOCUMENT)) { |
| 332 |
$element->{ caller } = $component->{ name }; |
| 333 |
$element->{ callers } = $component->{ callers } || []; |
| 334 |
push(@{$element->{ callers }}, $element->{ caller }); |
| 335 |
} |
| 336 |
|
| 337 |
$stash->set('component', $element); |
| 338 |
|
| 339 |
unless ($localize) { |
| 340 |
# merge any local blocks defined in the Template::Document |
| 341 |
# into our local BLOCKS cache |
| 342 |
@$blocks{ keys %$tblocks } = values %$tblocks |
| 343 |
if (blessed($compiled) && $compiled->isa(DOCUMENT)) |
| 344 |
&& ($tblocks = $compiled->blocks); |
| 345 |
} |
| 346 |
|
| 347 |
if (ref $compiled eq 'CODE') { |
| 348 |
$tmpout = &$compiled($self); |
| 349 |
} |
| 350 |
elsif (ref $compiled) { |
| 351 |
$tmpout = $compiled->process($self); |
| 352 |
} |
| 353 |
else { |
| 354 |
$self->throw('file', |
| 355 |
"invalid template reference: $compiled"); |
| 356 |
} |
| 357 |
|
| 358 |
if ($trim) { |
| 359 |
for ($tmpout) { |
| 360 |
s/^\s+//; |
| 361 |
s/\s+$//; |
| 362 |
} |
| 363 |
} |
| 364 |
$output .= $tmpout; |
| 365 |
|
| 366 |
# pop last item from callers. |
| 367 |
# NOTE - this will not be called if template throws an |
| 368 |
# error. The whole issue of caller and callers should be |
| 369 |
# revisited to try and avoid putting this info directly into |
| 370 |
# the component data structure. Perhaps use a local element |
| 371 |
# instead? |
| 372 |
|
| 373 |
pop(@{$element->{ callers }}) |
| 374 |
if (blessed($component) && $component->isa(DOCUMENT)); |
| 375 |
} |
| 376 |
$stash->set('component', $component); |
| 377 |
}; |
| 378 |
$error = $@; |
| 379 |
|
| 380 |
if ($localize) { |
| 381 |
# ensure stash is delocalised before dying |
| 382 |
$self->{ STASH } = $self->{ STASH }->declone(); |
| 383 |
} |
| 384 |
|
| 385 |
$self->throw(ref $error |
| 386 |
? $error : (Template::Constants::ERROR_FILE, $error)) |
| 387 |
if $error; |
| 388 |
|
| 389 |
return $output; |
| 390 |
} |
| 391 |
|
| 392 |
|
| 393 |
#------------------------------------------------------------------------ |
| 394 |
# include($template, \%params) [% INCLUDE template var = val, ... %] |
| 395 |
# |
| 396 |
# Similar to process() above but processing the template in a local |
| 397 |
# context. Any variables passed by reference to a hash as the second |
| 398 |
# parameter will be set before the template is processed and then |
| 399 |
# revert to their original values before the method returns. Similarly, |
| 400 |
# any changes made to non-global variables within the template will |
| 401 |
# persist only until the template is processed. |
| 402 |
# |
| 403 |
# Returns the output of processing the template. Errors are thrown |
| 404 |
# as Template::Exception objects via die(). |
| 405 |
#------------------------------------------------------------------------ |
| 406 |
|
| 407 |
sub include { |
| 408 |
my ($self, $template, $params) = @_; |
| 409 |
return $self->process($template, $params, 'localize me!'); |
| 410 |
} |
| 411 |
|
| 412 |
#------------------------------------------------------------------------ |
| 413 |
# insert($file) |
| 414 |
# |
| 415 |
# Insert the contents of a file without parsing. |
| 416 |
#------------------------------------------------------------------------ |
| 417 |
|
| 418 |
sub insert { |
| 419 |
my ($self, $file) = @_; |
| 420 |
my ($prefix, $providers, $text, $error); |
| 421 |
my $output = ''; |
| 422 |
|
| 423 |
my $files = ref $file eq 'ARRAY' ? $file : [ $file ]; |
| 424 |
|
| 425 |
$self->debug("insert([ ", join(', '), @$files, " ])") |
| 426 |
if $self->{ DEBUG }; |
| 427 |
|
| 428 |
|
| 429 |
FILE: foreach $file (@$files) { |
| 430 |
my $name = $file; |
| 431 |
|
| 432 |
if ($^O eq 'MSWin32') { |
| 433 |
# let C:/foo through |
| 434 |
$prefix = $1 if $name =~ s/^(\w{2,})://o; |
| 435 |
} |
| 436 |
else { |
| 437 |
$prefix = $1 if $name =~ s/^(\w+)://; |
| 438 |
} |
| 439 |
|
| 440 |
if (defined $prefix) { |
| 441 |
$providers = $self->{ PREFIX_MAP }->{ $prefix } |
| 442 |
|| return $self->throw(Template::Constants::ERROR_FILE, |
| 443 |
"no providers for file prefix '$prefix'"); |
| 444 |
} |
| 445 |
else { |
| 446 |
$providers = $self->{ PREFIX_MAP }->{ default } |
| 447 |
|| $self->{ LOAD_TEMPLATES }; |
| 448 |
} |
| 449 |
|
| 450 |
foreach my $provider (@$providers) { |
| 451 |
($text, $error) = $provider->load($name, $prefix); |
| 452 |
next FILE unless $error; |
| 453 |
if ($error == Template::Constants::STATUS_ERROR) { |
| 454 |
$self->throw($text) if ref $text; |
| 455 |
$self->throw(Template::Constants::ERROR_FILE, $text); |
| 456 |
} |
| 457 |
} |
| 458 |
$self->throw(Template::Constants::ERROR_FILE, "$file: not found"); |
| 459 |
} |
| 460 |
continue { |
| 461 |
$output .= $text; |
| 462 |
} |
| 463 |
return $output; |
| 464 |
} |
| 465 |
|
| 466 |
|
| 467 |
#------------------------------------------------------------------------ |
| 468 |
# throw($type, $info, \$output) [% THROW errtype "Error info" %] |
| 469 |
# |
| 470 |
# Throws a Template::Exception object by calling die(). This method |
| 471 |
# may be passed a reference to an existing Template::Exception object; |
| 472 |
# a single value containing an error message which is used to |
| 473 |
# instantiate a Template::Exception of type 'undef'; or a pair of |
| 474 |
# values representing the exception type and info from which a |
| 475 |
# Template::Exception object is instantiated. e.g. |
| 476 |
# |
| 477 |
# $context->throw($exception); |
| 478 |
# $context->throw("I'm sorry Dave, I can't do that"); |
| 479 |
# $context->throw('denied', "I'm sorry Dave, I can't do that"); |
| 480 |
# |
| 481 |
# An optional third parameter can be supplied in the last case which |
| 482 |
# is a reference to the current output buffer containing the results |
| 483 |
# of processing the template up to the point at which the exception |
| 484 |
# was thrown. The RETURN and STOP directives, for example, use this |
| 485 |
# to propagate output back to the user, but it can safely be ignored |
| 486 |
# in most cases. |
| 487 |
# |
| 488 |
# This method rides on a one-way ticket to die() oblivion. It does not |
| 489 |
# return in any real sense of the word, but should get caught by a |
| 490 |
# surrounding eval { } block (e.g. a BLOCK or TRY) and handled |
| 491 |
# accordingly, or returned to the caller as an uncaught exception. |
| 492 |
#------------------------------------------------------------------------ |
| 493 |
|
| 494 |
sub throw { |
| 495 |
my ($self, $error, $info, $output) = @_; |
| 496 |
local $" = ', '; |
| 497 |
|
| 498 |
# die! die! die! |
| 499 |
if (blessed($error) && $error->isa(EXCEPTION)) { |
| 500 |
die $error; |
| 501 |
} |
| 502 |
elsif (blessed($error) && $error->isa(BADGER_EXCEPTION)) { |
| 503 |
# convert a Badger::Exception to a Template::Exception so that |
| 504 |
# things continue to work during the transition to Badger |
| 505 |
die EXCEPTION->new($error->type, $error->info); |
| 506 |
} |
| 507 |
elsif (defined $info) { |
| 508 |
die (EXCEPTION->new($error, $info, $output)); |
| 509 |
} |
| 510 |
else { |
| 511 |
$error ||= ''; |
| 512 |
die (EXCEPTION->new('undef', $error, $output)); |
| 513 |
} |
| 514 |
|
| 515 |
# not reached |
| 516 |
} |
| 517 |
|
| 518 |
|
| 519 |
#------------------------------------------------------------------------ |
| 520 |
# catch($error, \$output) |
| 521 |
# |
| 522 |
# Called by various directives after catching an error thrown via die() |
| 523 |
# from within an eval { } block. The first parameter contains the errror |
| 524 |
# which may be a sanitized reference to a Template::Exception object |
| 525 |
# (such as that raised by the throw() method above, a plugin object, |
| 526 |
# and so on) or an error message thrown via die from somewhere in user |
| 527 |
# code. The latter are coerced into 'undef' Template::Exception objects. |
| 528 |
# Like throw() above, a reference to a scalar may be passed as an |
| 529 |
# additional parameter to represent the current output buffer |
| 530 |
# localised within the eval block. As exceptions are thrown upwards |
| 531 |
# and outwards from nested blocks, the catch() method reconstructs the |
| 532 |
# correct output buffer from these fragments, storing it in the |
| 533 |
# exception object for passing further onwards and upwards. |
| 534 |
# |
| 535 |
# Returns a reference to a Template::Exception object.. |
| 536 |
#------------------------------------------------------------------------ |
| 537 |
|
| 538 |
sub catch { |
| 539 |
my ($self, $error, $output) = @_; |
| 540 |
|
| 541 |
if ( blessed($error) |
| 542 |
&& ( $error->isa(EXCEPTION) || $error->isa(BADGER_EXCEPTION) ) ) { |
| 543 |
$error->text($output) if $output; |
| 544 |
return $error; |
| 545 |
} |
| 546 |
else { |
| 547 |
return EXCEPTION->new('undef', $error, $output); |
| 548 |
} |
| 549 |
} |
| 550 |
|
| 551 |
|
| 552 |
#------------------------------------------------------------------------ |
| 553 |
# localise(\%params) |
| 554 |
# delocalise() |
| 555 |
# |
| 556 |
# The localise() method creates a local copy of the current stash, |
| 557 |
# allowing the existing state of variables to be saved and later |
| 558 |
# restored via delocalise(). |
| 559 |
# |
| 560 |
# A reference to a hash array may be passed containing local variable |
| 561 |
# definitions which should be added to the cloned namespace. These |
| 562 |
# values persist until delocalisation. |
| 563 |
#------------------------------------------------------------------------ |
| 564 |
|
| 565 |
sub localise { |
| 566 |
my $self = shift; |
| 567 |
$self->{ STASH } = $self->{ STASH }->clone(@_); |
| 568 |
} |
| 569 |
|
| 570 |
sub delocalise { |
| 571 |
my $self = shift; |
| 572 |
$self->{ STASH } = $self->{ STASH }->declone(); |
| 573 |
} |
| 574 |
|
| 575 |
|
| 576 |
#------------------------------------------------------------------------ |
| 577 |
# visit($document, $blocks) |
| 578 |
# |
| 579 |
# Each Template::Document calls the visit() method on the context |
| 580 |
# before processing itself. It passes a reference to the hash array |
| 581 |
# of named BLOCKs defined within the document, allowing them to be |
| 582 |
# added to the internal BLKSTACK list which is subsequently used by |
| 583 |
# template() to resolve templates. |
| 584 |
# from a provider. |
| 585 |
#------------------------------------------------------------------------ |
| 586 |
|
| 587 |
sub visit { |
| 588 |
my ($self, $document, $blocks) = @_; |
| 589 |
unshift(@{ $self->{ BLKSTACK } }, $blocks) |
| 590 |
} |
| 591 |
|
| 592 |
|
| 593 |
#------------------------------------------------------------------------ |
| 594 |
# leave() |
| 595 |
# |
| 596 |
# The leave() method is called when the document has finished |
| 597 |
# processing itself. This removes the entry from the BLKSTACK list |
| 598 |
# that was added visit() above. For persistence of BLOCK definitions, |
| 599 |
# the process() method (i.e. the PROCESS directive) does some extra |
| 600 |
# magic to copy BLOCKs into a shared hash. |
| 601 |
#------------------------------------------------------------------------ |
| 602 |
|
| 603 |
sub leave { |
| 604 |
my $self = shift; |
| 605 |
shift(@{ $self->{ BLKSTACK } }); |
| 606 |
} |
| 607 |
|
| 608 |
|
| 609 |
#------------------------------------------------------------------------ |
| 610 |
# define_block($name, $block) |
| 611 |
# |
| 612 |
# Adds a new BLOCK definition to the local BLOCKS cache. $block may |
| 613 |
# be specified as a reference to a sub-routine or Template::Document |
| 614 |
# object or as text which is compiled into a template. Returns a true |
| 615 |
# value (the $block reference or compiled block reference) if |
| 616 |
# successful or undef on failure. Call error() to retrieve the |
| 617 |
# relevent error message (i.e. compilation failure). |
| 618 |
#------------------------------------------------------------------------ |
| 619 |
|
| 620 |
sub define_block { |
| 621 |
my ($self, $name, $block) = @_; |
| 622 |
$block = $self->template(\$block) |
| 623 |
|| return undef |
| 624 |
unless ref $block; |
| 625 |
$self->{ BLOCKS }->{ $name } = $block; |
| 626 |
} |
| 627 |
|
| 628 |
|
| 629 |
#------------------------------------------------------------------------ |
| 630 |
# define_filter($name, $filter, $is_dynamic) |
| 631 |
# |
| 632 |
# Adds a new FILTER definition to the local FILTER_CACHE. |
| 633 |
#------------------------------------------------------------------------ |
| 634 |
|
| 635 |
sub define_filter { |
| 636 |
my ($self, $name, $filter, $is_dynamic) = @_; |
| 637 |
my ($result, $error); |
| 638 |
$filter = [ $filter, 1 ] if $is_dynamic; |
| 639 |
|
| 640 |
foreach my $provider (@{ $self->{ LOAD_FILTERS } }) { |
| 641 |
($result, $error) = $provider->store($name, $filter); |
| 642 |
return 1 unless $error; |
| 643 |
$self->throw(&Template::Constants::ERROR_FILTER, $result) |
| 644 |
if $error == &Template::Constants::STATUS_ERROR; |
| 645 |
} |
| 646 |
$self->throw(&Template::Constants::ERROR_FILTER, |
| 647 |
"FILTER providers declined to store filter $name"); |
| 648 |
} |
| 649 |
|
| 650 |
sub define_view { |
| 651 |
my ($self, $name, $params) = @_; |
| 652 |
my $base; |
| 653 |
|
| 654 |
if (defined $params->{ base }) { |
| 655 |
my $base = $self->{ STASH }->get($params->{ base }); |
| 656 |
|
| 657 |
return $self->throw( |
| 658 |
&Template::Constants::ERROR_VIEW, |
| 659 |
"view base is not defined: $params->{ base }" |
| 660 |
) unless $base; |
| 661 |
|
| 662 |
return $self->throw( |
| 663 |
&Template::Constants::ERROR_VIEW, |
| 664 |
"view base is not a $VIEW_CLASS object: $params->{ base } => $base" |
| 665 |
) unless blessed($base) && $base->isa($VIEW_CLASS); |
| 666 |
|
| 667 |
$params->{ base } = $base; |
| 668 |
} |
| 669 |
my $view = $self->view($params); |
| 670 |
$view->seal(); |
| 671 |
$self->{ STASH }->set($name, $view); |
| 672 |
} |
| 673 |
|
| 674 |
sub define_views { |
| 675 |
my ($self, $views) = @_; |
| 676 |
|
| 677 |
# a list reference is better because the order is deterministic (and so |
| 678 |
# allows an earlier VIEW to be the base for a later VIEW), but we'll |
| 679 |
# accept a hash reference and assume that the user knows the order of |
| 680 |
# processing is undefined |
| 681 |
$views = [ %$views ] |
| 682 |
if ref $views eq 'HASH'; |
| 683 |
|
| 684 |
# make of copy so we don't destroy the original list reference |
| 685 |
my @items = @$views; |
| 686 |
my ($name, $view); |
| 687 |
|
| 688 |
while (@items) { |
| 689 |
$self->define_view(splice(@items, 0, 2)); |
| 690 |
} |
| 691 |
} |
| 692 |
|
| 693 |
|
| 694 |
#------------------------------------------------------------------------ |
| 695 |
# reset() |
| 696 |
# |
| 697 |
# Reset the state of the internal BLOCKS hash to clear any BLOCK |
| 698 |
# definitions imported via the PROCESS directive. Any original |
| 699 |
# BLOCKS definitions passed to the constructor will be restored. |
| 700 |
#------------------------------------------------------------------------ |
| 701 |
|
| 702 |
sub reset { |
| 703 |
my ($self, $blocks) = @_; |
| 704 |
$self->{ BLKSTACK } = [ ]; |
| 705 |
$self->{ BLOCKS } = { %{ $self->{ INIT_BLOCKS } } }; |
| 706 |
} |
| 707 |
|
| 708 |
|
| 709 |
#------------------------------------------------------------------------ |
| 710 |
# stash() |
| 711 |
# |
| 712 |
# Simple accessor methods to return the STASH values. This is likely |
| 713 |
# to be called quite often so we provide a direct method rather than |
| 714 |
# relying on the slower AUTOLOAD. |
| 715 |
#------------------------------------------------------------------------ |
| 716 |
|
| 717 |
sub stash { |
| 718 |
return $_[0]->{ STASH }; |
| 719 |
} |
| 720 |
|
| 721 |
|
| 722 |
#------------------------------------------------------------------------ |
| 723 |
# define_vmethod($type, $name, \&sub) |
| 724 |
# |
| 725 |
# Passes $type, $name, and &sub on to stash->define_vmethod(). |
| 726 |
#------------------------------------------------------------------------ |
| 727 |
sub define_vmethod { |
| 728 |
my $self = shift; |
| 729 |
$self->stash->define_vmethod(@_); |
| 730 |
} |
| 731 |
|
| 732 |
|
| 733 |
#------------------------------------------------------------------------ |
| 734 |
# debugging($command, @args, \%params) |
| 735 |
# |
| 736 |
# Method for controlling the debugging status of the context. The first |
| 737 |
# argument can be 'on' or 'off' to enable/disable debugging, 'format' |
| 738 |
# to define the format of the debug message, or 'msg' to generate a |
| 739 |
# debugging message reporting the file, line, message text, etc., |
| 740 |
# according to the current debug format. |
| 741 |
#------------------------------------------------------------------------ |
| 742 |
|
| 743 |
sub debugging { |
| 744 |
my $self = shift; |
| 745 |
my $hash = ref $_[-1] eq 'HASH' ? pop : { }; |
| 746 |
my @args = @_; |
| 747 |
|
| 748 |
# print "*** debug(@args)\n"; |
| 749 |
if (@args) { |
| 750 |
if ($args[0] =~ /^on|1$/i) { |
| 751 |
$self->{ DEBUG_DIRS } = 1; |
| 752 |
shift(@args); |
| 753 |
} |
| 754 |
elsif ($args[0] =~ /^off|0$/i) { |
| 755 |
$self->{ DEBUG_DIRS } = 0; |
| 756 |
shift(@args); |
| 757 |
} |
| 758 |
} |
| 759 |
|
| 760 |
if (@args) { |
| 761 |
if ($args[0] =~ /^msg$/i) { |
| 762 |
return unless $self->{ DEBUG_DIRS }; |
| 763 |
my $format = $self->{ DEBUG_FORMAT }; |
| 764 |
$format = $DEBUG_FORMAT unless defined $format; |
| 765 |
$format =~ s/\$(\w+)/$hash->{ $1 }/ge; |
| 766 |
return $format; |
| 767 |
} |
| 768 |
elsif ($args[0] =~ /^format$/i) { |
| 769 |
$self->{ DEBUG_FORMAT } = $args[1]; |
| 770 |
} |
| 771 |
# else ignore |
| 772 |
} |
| 773 |
|
| 774 |
return ''; |
| 775 |
} |
| 776 |
|
| 777 |
|
| 778 |
#------------------------------------------------------------------------ |
| 779 |
# AUTOLOAD |
| 780 |
# |
| 781 |
# Provides pseudo-methods for read-only access to various internal |
| 782 |
# members. For example, templates(), plugins(), filters(), |
| 783 |
# eval_perl(), load_perl(), etc. These aren't called very often, or |
| 784 |
# may never be called at all. |
| 785 |
#------------------------------------------------------------------------ |
| 786 |
|
| 787 |
sub AUTOLOAD { |
| 788 |
my $self = shift; |
| 789 |
my $method = $AUTOLOAD; |
| 790 |
my $result; |
| 791 |
|
| 792 |
$method =~ s/.*:://; |
| 793 |
return if $method eq 'DESTROY'; |
| 794 |
|
| 795 |
warn "no such context method/member: $method\n" |
| 796 |
unless defined ($result = $self->{ uc $method }); |
| 797 |
|
| 798 |
return $result; |
| 799 |
} |
| 800 |
|
| 801 |
|
| 802 |
#------------------------------------------------------------------------ |
| 803 |
# DESTROY |
| 804 |
# |
| 805 |
# Stash may contain references back to the Context via macro closures, |
| 806 |
# etc. This breaks the circular references. |
| 807 |
#------------------------------------------------------------------------ |
| 808 |
|
| 809 |
sub DESTROY { |
| 810 |
my $self = shift; |
| 811 |
undef $self->{ STASH }; |
| 812 |
} |
| 813 |
|
| 814 |
|
| 815 |
|
| 816 |
#======================================================================== |
| 817 |
# -- PRIVATE METHODS -- |
| 818 |
#======================================================================== |
| 819 |
|
| 820 |
#------------------------------------------------------------------------ |
| 821 |
# _init(\%config) |
| 822 |
# |
| 823 |
# Initialisation method called by Template::Base::new() |
| 824 |
#------------------------------------------------------------------------ |
| 825 |
|
| 826 |
sub _init { |
| 827 |
my ($self, $config) = @_; |
| 828 |
my ($name, $item, $method, $block, $blocks); |
| 829 |
my @itemlut = ( |
| 830 |
LOAD_TEMPLATES => 'provider', |
| 831 |
LOAD_PLUGINS => 'plugins', |
| 832 |
LOAD_FILTERS => 'filters' |
| 833 |
); |
| 834 |
|
| 835 |
# LOAD_TEMPLATE, LOAD_PLUGINS, LOAD_FILTERS - lists of providers |
| 836 |
while (($name, $method) = splice(@itemlut, 0, 2)) { |
| 837 |
$item = $config->{ $name } |
| 838 |
|| Template::Config->$method($config) |
| 839 |
|| return $self->error($Template::Config::ERROR); |
| 840 |
$self->{ $name } = ref $item eq 'ARRAY' ? $item : [ $item ]; |
| 841 |
} |
| 842 |
|
| 843 |
my $providers = $self->{ LOAD_TEMPLATES }; |
| 844 |
my $prefix_map = $self->{ PREFIX_MAP } = $config->{ PREFIX_MAP } || { }; |
| 845 |
while (my ($key, $val) = each %$prefix_map) { |
| 846 |
$prefix_map->{ $key } = [ ref $val ? $val : |
| 847 |
map { $providers->[$_] } split(/\D+/, $val) ] |
| 848 |
unless ref $val eq 'ARRAY'; |
| 849 |
} |
| 850 |
|
| 851 |
# STASH |
| 852 |
$self->{ STASH } = $config->{ STASH } || do { |
| 853 |
my $predefs = $config->{ VARIABLES } |
| 854 |
|| $config->{ PRE_DEFINE } |
| 855 |
|| { }; |
| 856 |
|
| 857 |
# hack to get stash to know about debug mode |
| 858 |
$predefs->{ _DEBUG } = ( ($config->{ DEBUG } || 0) |
| 859 |
& &Template::Constants::DEBUG_UNDEF ) ? 1 : 0 |
| 860 |
unless defined $predefs->{ _DEBUG }; |
| 861 |
$predefs->{ _STRICT } = $config->{ STRICT }; |
| 862 |
|
| 863 |
Template::Config->stash($predefs) |
| 864 |
|| return $self->error($Template::Config::ERROR); |
| 865 |
}; |
| 866 |
|
| 867 |
# compile any template BLOCKS specified as text |
| 868 |
$blocks = $config->{ BLOCKS } || { }; |
| 869 |
$self->{ INIT_BLOCKS } = $self->{ BLOCKS } = { |
| 870 |
map { |
| 871 |
$block = $blocks->{ $_ }; |
| 872 |
$block = $self->template(\$block) |
| 873 |
|| return undef |
| 874 |
unless ref $block; |
| 875 |
($_ => $block); |
| 876 |
} |
| 877 |
keys %$blocks |
| 878 |
}; |
| 879 |
|
| 880 |
# define any VIEWS |
| 881 |
$self->define_views( $config->{ VIEWS } ) |
| 882 |
if $config->{ VIEWS }; |
| 883 |
|
| 884 |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| 885 |
# RECURSION - flag indicating is recursion into templates is supported |
| 886 |
# EVAL_PERL - flag indicating if PERL blocks should be processed |
| 887 |
# TRIM - flag to remove leading and trailing whitespace from output |
| 888 |
# BLKSTACK - list of hashes of BLOCKs defined in current template(s) |
| 889 |
# CONFIG - original configuration hash |
| 890 |
# EXPOSE_BLOCKS - make blocks visible as pseudo-files |
| 891 |
# DEBUG_FORMAT - format for generating template runtime debugging messages |
| 892 |
# DEBUG - format for generating template runtime debugging messages |
| 893 |
|
| 894 |
$self->{ RECURSION } = $config->{ RECURSION } || 0; |
| 895 |
$self->{ EVAL_PERL } = $config->{ EVAL_PERL } || 0; |
| 896 |
$self->{ TRIM } = $config->{ TRIM } || 0; |
| 897 |
$self->{ BLKSTACK } = [ ]; |
| 898 |
$self->{ CONFIG } = $config; |
| 899 |
$self->{ EXPOSE_BLOCKS } = defined $config->{ EXPOSE_BLOCKS } |
| 900 |
? $config->{ EXPOSE_BLOCKS } |
| 901 |
: 0; |
| 902 |
|
| 903 |
$self->{ DEBUG_FORMAT } = $config->{ DEBUG_FORMAT }; |
| 904 |
$self->{ DEBUG_DIRS } = ($config->{ DEBUG } || 0) |
| 905 |
& Template::Constants::DEBUG_DIRS; |
| 906 |
$self->{ DEBUG } = defined $config->{ DEBUG } |
| 907 |
? $config->{ DEBUG } & ( Template::Constants::DEBUG_CONTEXT |
| 908 |
| Template::Constants::DEBUG_FLAGS ) |
| 909 |
: $DEBUG; |
| 910 |
|
| 911 |
return $self; |
| 912 |
} |
| 913 |
|
| 914 |
|
| 915 |
#------------------------------------------------------------------------ |
| 916 |
# _dump() |
| 917 |
# |
| 918 |
# Debug method which returns a string representing the internal state |
| 919 |
# of the context object. |
| 920 |
#------------------------------------------------------------------------ |
| 921 |
|
| 922 |
sub _dump { |
| 923 |
my $self = shift; |
| 924 |
my $output = "[Template::Context] {\n"; |
| 925 |
my $format = " %-16s => %s\n"; |
| 926 |
my $key; |
| 927 |
|
| 928 |
foreach $key (qw( RECURSION EVAL_PERL TRIM )) { |
| 929 |
$output .= sprintf($format, $key, $self->{ $key }); |
| 930 |
} |
| 931 |
foreach my $pname (qw( LOAD_TEMPLATES LOAD_PLUGINS LOAD_FILTERS )) { |
| 932 |
my $provtext = "[\n"; |
| 933 |
foreach my $prov (@{ $self->{ $pname } }) { |
| 934 |
$provtext .= $prov->_dump(); |
| 935 |
# $provtext .= ",\n"; |
| 936 |
} |
| 937 |
$provtext =~ s/\n/\n /g; |
| 938 |
$provtext =~ s/\s+$//; |
| 939 |
$provtext .= ",\n ]"; |
| 940 |
$output .= sprintf($format, $pname, $provtext); |
| 941 |
} |
| 942 |
$output .= sprintf($format, STASH => $self->{ STASH }->_dump()); |
| 943 |
$output .= '}'; |
| 944 |
return $output; |
| 945 |
} |
| 946 |
|
| 947 |
|
| 948 |
1; |
| 949 |
|
| 950 |
__END__ |
| 951 |
|
| 952 |
=head1 NAME |
| 953 |
|
| 954 |
Template::Context - Runtime context in which templates are processed |
| 955 |
|
| 956 |
=head1 SYNOPSIS |
| 957 |
|
| 958 |
use Template::Context; |
| 959 |
|
| 960 |
# constructor |
| 961 |
$context = Template::Context->new(\%config) |
| 962 |
|| die $Template::Context::ERROR; |
| 963 |
|
| 964 |
# fetch (load and compile) a template |
| 965 |
$template = $context->template($template_name); |
| 966 |
|
| 967 |
# fetch (load and instantiate) a plugin object |
| 968 |
$plugin = $context->plugin($name, \@args); |
| 969 |
|
| 970 |
# fetch (return or create) a filter subroutine |
| 971 |
$filter = $context->filter($name, \@args, $alias); |
| 972 |
|
| 973 |
# process/include a template, errors are thrown via die() |
| 974 |
$output = $context->process($template, \%vars); |
| 975 |
$output = $context->include($template, \%vars); |
| 976 |
|
| 977 |
# raise an exception via die() |
| 978 |
$context->throw($error_type, $error_message, \$output_buffer); |
| 979 |
|
| 980 |
# catch an exception, clean it up and fix output buffer |
| 981 |
$exception = $context->catch($exception, \$output_buffer); |
| 982 |
|
| 983 |
# save/restore the stash to effect variable localisation |
| 984 |
$new_stash = $context->localise(\%vars); |
| 985 |
$old_stash = $context->delocalise(); |
| 986 |
|
| 987 |
# add new BLOCK or FILTER definitions |
| 988 |
$context->define_block($name, $block); |
| 989 |
$context->define_filter($name, \&filtersub, $is_dynamic); |
| 990 |
|
| 991 |
# reset context, clearing any imported BLOCK definitions |
| 992 |
$context->reset(); |
| 993 |
|
| 994 |
# methods for accessing internal items |
| 995 |
$stash = $context->stash(); |
| 996 |
$tflag = $context->trim(); |
| 997 |
$epflag = $context->eval_perl(); |
| 998 |
$providers = $context->templates(); |
| 999 |
$providers = $context->plugins(); |
| 1000 |
$providers = $context->filters(); |
| 1001 |
... |
| 1002 |
|
| 1003 |
=head1 DESCRIPTION |
| 1004 |
|
| 1005 |
The C<Template::Context> module defines an object class for representing |
| 1006 |
a runtime context in which templates are processed. It provides an |
| 1007 |
interface to the fundamental operations of the Template Toolkit |
| 1008 |
processing engine through which compiled templates (i.e. Perl code |
| 1009 |
constructed from the template source) can process templates, load |
| 1010 |
plugins and filters, raise exceptions and so on. |
| 1011 |
|
| 1012 |
A default C<Template::Context> object is created by the L<Template> module. |
| 1013 |
Any C<Template::Context> options may be passed to the L<Template> |
| 1014 |
L<new()|Template#new()> constructor method and will be forwarded to the |
| 1015 |
C<Template::Context> constructor. |
| 1016 |
|
| 1017 |
use Template; |
| 1018 |
|
| 1019 |
my $template = Template->new({ |
| 1020 |
TRIM => 1, |
| 1021 |
EVAL_PERL => 1, |
| 1022 |
BLOCKS => { |
| 1023 |
header => 'This is the header', |
| 1024 |
footer => 'This is the footer', |
| 1025 |
}, |
| 1026 |
}); |
| 1027 |
|
| 1028 |
Similarly, the C<Template::Context> constructor will forward all configuration |
| 1029 |
parameters onto other default objects (e.g. L<Template::Provider>, |
| 1030 |
L<Template::Plugins>, L<Template::Filters>, etc.) that it may need to |
| 1031 |
instantiate. |
| 1032 |
|
| 1033 |
$context = Template::Context->new({ |
| 1034 |
INCLUDE_PATH => '/home/abw/templates', # provider option |
| 1035 |
TAG_STYLE => 'html', # parser option |
| 1036 |
}); |
| 1037 |
|
| 1038 |
A C<Template::Context> object (or subclass) can be explicitly instantiated and |
| 1039 |
passed to the L<Template> L<new()|Template#new()> constructor method as the |
| 1040 |
C<CONTEXT> configuration item. |
| 1041 |
|
| 1042 |
use Template; |
| 1043 |
use Template::Context; |
| 1044 |
|
| 1045 |
my $context = Template::Context->new({ TRIM => 1 }); |
| 1046 |
my $template = Template->new({ CONTEXT => $context }); |
| 1047 |
|
| 1048 |
The L<Template> module uses the L<Template::Config> |
| 1049 |
L<context()|Template::Config#context()> factory method to create a default |
| 1050 |
context object when required. The C<$Template::Config::CONTEXT> package |
| 1051 |
variable may be set to specify an alternate context module. This will be |
| 1052 |
loaded automatically and its L<new()> constructor method called by the |
| 1053 |
L<context()|Template::Config#context()> factory method when a default context |
| 1054 |
object is required. |
| 1055 |
|
| 1056 |
use Template; |
| 1057 |
|
| 1058 |
$Template::Config::CONTEXT = 'MyOrg::Template::Context'; |
| 1059 |
|
| 1060 |
my $template = Template->new({ |
| 1061 |
EVAL_PERL => 1, |
| 1062 |
EXTRA_MAGIC => 'red hot', # your extra config items |
| 1063 |
... |
| 1064 |
}); |
| 1065 |
|
| 1066 |
=head1 METHODS |
| 1067 |
|
| 1068 |
=head2 new(\%params) |
| 1069 |
|
| 1070 |
The C<new()> constructor method is called to instantiate a |
| 1071 |
C<Template::Context> object. Configuration parameters may be specified as a |
| 1072 |
HASH reference or as a list of C<name =E<gt> value> pairs. |
| 1073 |
|
| 1074 |
my $context = Template::Context->new({ |
| 1075 |
INCLUDE_PATH => 'header', |
| 1076 |
POST_PROCESS => 'footer', |
| 1077 |
}); |
| 1078 |
|
| 1079 |
my $context = Template::Context->new( EVAL_PERL => 1 ); |
| 1080 |
|
| 1081 |
The C<new()> method returns a C<Template::Context> object or C<undef> on |
| 1082 |
error. In the latter case, a relevant error message can be retrieved by the |
| 1083 |
L<error()|Template::Base#error()> class method or directly from the |
| 1084 |
C<$Template::Context::ERROR> package variable. |
| 1085 |
|
| 1086 |
my $context = Template::Context->new(\%config) |
| 1087 |
|| die Template::Context->error(); |
| 1088 |
|
| 1089 |
my $context = Template::Context->new(\%config) |
| 1090 |
|| die $Template::Context::ERROR; |
| 1091 |
|
| 1092 |
The following configuration items may be specified. Please see |
| 1093 |
L<Template::Manual::Config> for further details. |
| 1094 |
|
| 1095 |
=head3 VARIABLES |
| 1096 |
|
| 1097 |
The L<VARIABLES|Template::Manual::Config#VARIABLES> option can be used to |
| 1098 |
specify a hash array of template variables. |
| 1099 |
|
| 1100 |
my $context = Template::Context->new({ |
| 1101 |
VARIABLES => { |
| 1102 |
title => 'A Demo Page', |
| 1103 |
author => 'Joe Random Hacker', |
| 1104 |
version => 3.14, |
| 1105 |
}, |
| 1106 |
}; |
| 1107 |
|
| 1108 |
=head3 BLOCKS |
| 1109 |
|
| 1110 |
The L<BLOCKS|Template::Manual::Config#BLOCKS> option can be used to pre-define |
| 1111 |
a default set of template blocks. |
| 1112 |
|
| 1113 |
my $context = Template::Context->new({ |
| 1114 |
BLOCKS => { |
| 1115 |
header => 'The Header. [% title %]', |
| 1116 |
footer => sub { return $some_output_text }, |
| 1117 |
another => Template::Document->new({ ... }), |
| 1118 |
}, |
| 1119 |
}); |
| 1120 |
|
| 1121 |
=head3 VIEWS |
| 1122 |
|
| 1123 |
The L<VIEWS|Template::Manual::Config#VIEWS> option can be used to pre-define |
| 1124 |
one or more L<Template::View> objects. |
| 1125 |
|
| 1126 |
my $context = Template::Context->new({ |
| 1127 |
VIEWS => [ |
| 1128 |
bottom => { prefix => 'bottom/' }, |
| 1129 |
middle => { prefix => 'middle/', base => 'bottom' }, |
| 1130 |
top => { prefix => 'top/', base => 'middle' }, |
| 1131 |
], |
| 1132 |
}); |
| 1133 |
|
| 1134 |
=head3 TRIM |
| 1135 |
|
| 1136 |
The L<TRIM|Template::Manual::Config#TRIM> option can be set to have any |
| 1137 |
leading and trailing whitespace automatically removed from the output of all |
| 1138 |
template files and C<BLOCK>s. |
| 1139 |
|
| 1140 |
example: |
| 1141 |
|
| 1142 |
[% BLOCK foo %] |
| 1143 |
|
| 1144 |
Line 1 of foo |
| 1145 |
|
| 1146 |
[% END %] |
| 1147 |
|
| 1148 |
before |
| 1149 |
[% INCLUDE foo %] |
| 1150 |
after |
| 1151 |
|
| 1152 |
output: |
| 1153 |
|
| 1154 |
before |
| 1155 |
Line 1 of foo |
| 1156 |
after |
| 1157 |
|
| 1158 |
=head3 EVAL_PERL |
| 1159 |
|
| 1160 |
The L<EVAL_PERL|Template::Manual::Config#EVAL_PERL> is used to indicate if |
| 1161 |
C<PERL> and/or C<RAWPERL> blocks should be evaluated. It is disabled by |
| 1162 |
default. |
| 1163 |
|
| 1164 |
=head3 RECURSION |
| 1165 |
|
| 1166 |
The L<RECURSION|Template::Manual::Config#RECURSION> can be set to |
| 1167 |
allow templates to recursively process themselves, either directly |
| 1168 |
(e.g. template C<foo> calls C<INCLUDE foo>) or indirectly (e.g. |
| 1169 |
C<foo> calls C<INCLUDE bar> which calls C<INCLUDE foo>). |
| 1170 |
|
| 1171 |
=head3 LOAD_TEMPLATES |
| 1172 |
|
| 1173 |
The L<LOAD_TEMPLATES|Template::Manual::Config#LOAD_TEMPLATES> option can be |
| 1174 |
used to provide a reference to a list of L<Template::Provider> objects or |
| 1175 |
sub-classes thereof which will take responsibility for loading and compiling |
| 1176 |
templates. |
| 1177 |
|
| 1178 |
my $context = Template::Context->new({ |
| 1179 |
LOAD_TEMPLATES => [ |
| 1180 |
MyOrg::Template::Provider->new({ ... }), |
| 1181 |
Template::Provider->new({ ... }), |
| 1182 |
], |
| 1183 |
}); |
| 1184 |
|
| 1185 |
=head3 LOAD_PLUGINS |
| 1186 |
|
| 1187 |
The L<LOAD_PLUGINS|Template::Manual::Config#LOAD_PLUGINS> options can be used |
| 1188 |
to specify a list of provider objects responsible for loading and |
| 1189 |
instantiating template plugin objects. |
| 1190 |
|
| 1191 |
my $context = Template::Context->new({ |
| 1192 |
LOAD_PLUGINS => [ |
| 1193 |
MyOrg::Template::Plugins->new({ ... }), |
| 1194 |
Template::Plugins->new({ ... }), |
| 1195 |
], |
| 1196 |
}); |
| 1197 |
|
| 1198 |
=head3 LOAD_FILTERS |
| 1199 |
|
| 1200 |
The L<LOAD_FILTERS|Template::Manual::Config#LOAD_FILTERS> option can be used |
| 1201 |
to specify a list of provider objects for returning and/or creating filter |
| 1202 |
subroutines. |
| 1203 |
|
| 1204 |
my $context = Template::Context->new({ |
| 1205 |
LOAD_FILTERS => [ |
| 1206 |
MyTemplate::Filters->new(), |
| 1207 |
Template::Filters->new(), |
| 1208 |
], |
| 1209 |
}); |
| 1210 |
|
| 1211 |
=head3 STASH |
| 1212 |
|
| 1213 |
The L<STASH|Template::Manual::Config#STASH> option can be used to |
| 1214 |
specify a L<Template::Stash> object or sub-class which will take |
| 1215 |
responsibility for managing template variables. |
| 1216 |
|
| 1217 |
my $stash = MyOrg::Template::Stash->new({ ... }); |
| 1218 |
my $context = Template::Context->new({ |
| 1219 |
STASH => $stash, |
| 1220 |
}); |
| 1221 |
|
| 1222 |
=head3 DEBUG |
| 1223 |
|
| 1224 |
The L<DEBUG|Template::Manual::Config#DEBUG> option can be used to enable |
| 1225 |
various debugging features of the L<Template::Context> module. |
| 1226 |
|
| 1227 |
use Template::Constants qw( :debug ); |
| 1228 |
|
| 1229 |
my $template = Template->new({ |
| 1230 |
DEBUG => DEBUG_CONTEXT | DEBUG_DIRS, |
| 1231 |
}); |
| 1232 |
|
| 1233 |
=head2 template($name) |
| 1234 |
|
| 1235 |
Returns a compiled template by querying each of the L<LOAD_TEMPLATES> providers |
| 1236 |
(instances of L<Template::Provider>, or sub-class) in turn. |
| 1237 |
|
| 1238 |
$template = $context->template('header'); |
| 1239 |
|
| 1240 |
On error, a L<Template::Exception> object of type 'C<file>' is thrown via |
| 1241 |
C<die()>. This can be caught by enclosing the call to C<template()> in an |
| 1242 |
C<eval> block and examining C<$@>. |
| 1243 |
|
| 1244 |
eval { $template = $context->template('header') }; |
| 1245 |
if ($@) { |
| 1246 |
print "failed to fetch template: $@\n"; |
| 1247 |
} |
| 1248 |
|
| 1249 |
=head2 plugin($name, \@args) |
| 1250 |
|
| 1251 |
Instantiates a plugin object by querying each of the L<LOAD_PLUGINS> |
| 1252 |
providers. The default L<LOAD_PLUGINS> provider is a L<Template::Plugins> |
| 1253 |
object which attempts to load plugin modules, according the various |
| 1254 |
configuration items such as L<PLUGIN_BASE|Template::Plugins#PLUGIN_BASE>, |
| 1255 |
L<LOAD_PERL|Template::Plugins#LOAD_PERL>, etc., and then instantiate an object |
| 1256 |
via L<new()|Template::Plugin#new()>. A reference to a list of constructor |
| 1257 |
arguments may be passed as the second parameter. These are forwarded to the |
| 1258 |
plugin constructor. |
| 1259 |
|
| 1260 |
Returns a reference to a plugin (which is generally an object, but |
| 1261 |
doesn't have to be). Errors are thrown as L<Template::Exception> objects |
| 1262 |
with the type set to 'C<plugin>'. |
| 1263 |
|
| 1264 |
$plugin = $context->plugin('DBI', 'dbi:msql:mydbname'); |
| 1265 |
|
| 1266 |
=head2 filter($name, \@args, $alias) |
| 1267 |
|
| 1268 |
Instantiates a filter subroutine by querying the L<LOAD_FILTERS> providers. |
| 1269 |
The default L<LOAD_FILTERS> provider is a L<Template::Filters> object. |
| 1270 |
|
| 1271 |
Additional arguments may be passed by list reference along with an optional |
| 1272 |
alias under which the filter will be cached for subsequent use. The filter is |
| 1273 |
cached under its own C<$name> if C<$alias> is undefined. Subsequent calls to |
| 1274 |
C<filter($name)> will return the cached entry, if defined. Specifying arguments |
| 1275 |
bypasses the caching mechanism and always creates a new filter. Errors are |
| 1276 |
thrown as L<Template::Exception> objects with the type set to 'C<filter>'. |
| 1277 |
|
| 1278 |
# static filter (no args) |
| 1279 |
$filter = $context->filter('html'); |
| 1280 |
|
| 1281 |
# dynamic filter (args) aliased to 'padright' |
| 1282 |
$filter = $context->filter('format', '%60s', 'padright'); |
| 1283 |
|
| 1284 |
# retrieve previous filter via 'padright' alias |
| 1285 |
$filter = $context->filter('padright'); |
| 1286 |
|
| 1287 |
=head2 process($template, \%vars) |
| 1288 |
|
| 1289 |
Processes a template named or referenced by the first parameter and returns |
| 1290 |
the output generated. An optional reference to a hash array may be passed |
| 1291 |
as the second parameter, containing variable definitions which will be set |
| 1292 |
before the template is processed. The template is processed in the current |
| 1293 |
context, with no localisation of variables performed. Errors are thrown |
| 1294 |
as L<Template::Exception> objects via C<die()>. |
| 1295 |
|
| 1296 |
$output = $context->process('header', { title => 'Hello World' }); |
| 1297 |
|
| 1298 |
=head2 include($template, \%vars) |
| 1299 |
|
| 1300 |
Similar to L<process()>, but using localised variables. Changes made to |
| 1301 |
any variables will only persist until the C<include()> method completes. |
| 1302 |
|
| 1303 |
$output = $context->include('header', { title => 'Hello World' }); |
| 1304 |
|
| 1305 |
=head2 throw($error_type, $error_message, \$output) |
| 1306 |
|
| 1307 |
Raises an exception in the form of a L<Template::Exception> object by calling |
| 1308 |
C<die()>. This method may be passed a reference to an existing |
| 1309 |
L<Template::Exception> object; a single value containing an error message |
| 1310 |
which is used to instantiate a L<Template::Exception> of type 'C<undef>'; or a |
| 1311 |
pair of values representing the exception C<type> and C<info> from which a |
| 1312 |
L<Template::Exception> object is instantiated. e.g. |
| 1313 |
|
| 1314 |
$context->throw($exception); |
| 1315 |
$context->throw("I'm sorry Dave, I can't do that"); |
| 1316 |
$context->throw('denied', "I'm sorry Dave, I can't do that"); |
| 1317 |
|
| 1318 |
The optional third parameter may be a reference to the current output |
| 1319 |
buffer. This is then stored in the exception object when created, |
| 1320 |
allowing the catcher to examine and use the output up to the point at |
| 1321 |
which the exception was raised. |
| 1322 |
|
| 1323 |
$output .= 'blah blah blah'; |
| 1324 |
$output .= 'more rhubarb'; |
| 1325 |
$context->throw('yack', 'Too much yacking', \$output); |
| 1326 |
|
| 1327 |
=head2 catch($exception, \$output) |
| 1328 |
|
| 1329 |
Catches an exception thrown, either as a reference to a L<Template::Exception> |
| 1330 |
object or some other value. In the latter case, the error string is promoted |
| 1331 |
to a L<Template::Exception> object of 'C<undef>' type. This method also |
| 1332 |
accepts a reference to the current output buffer which is passed to the |
| 1333 |
L<Template::Exception> constructor, or is appended to the output buffer stored |
| 1334 |
in an existing L<Template::Exception> object, if unique (i.e. not the same |
| 1335 |
reference). By this process, the correct state of the output buffer can be |
| 1336 |
reconstructed for simple or nested throws. |
| 1337 |
|
| 1338 |
=head2 define_block($name, $block) |
| 1339 |
|
| 1340 |
Adds a new block definition to the internal L<BLOCKS> cache. The first |
| 1341 |
argument should contain the name of the block and the second a reference |
| 1342 |
to a L<Template::Document> object or template sub-routine, or template text |
| 1343 |
which is automatically compiled into a template sub-routine. |
| 1344 |
|
| 1345 |
Returns a true value (the sub-routine or L<Template::Document> reference) on |
| 1346 |
success or undef on failure. The relevant error message can be retrieved by |
| 1347 |
calling the L<error()|Template::Base#error()> method. |
| 1348 |
|
| 1349 |
=head2 define_filter($name, \&filter, $is_dynamic) |
| 1350 |
|
| 1351 |
Adds a new filter definition by calling the |
| 1352 |
L<store()|Template::Filters#store()> method on each of the L<LOAD_FILTERS> |
| 1353 |
providers until accepted (in the usual case, this is accepted straight away by |
| 1354 |
the one and only L<Template::Filters> provider). The first argument should |
| 1355 |
contain the name of the filter and the second a reference to a filter |
| 1356 |
subroutine. The optional third argument can be set to any true value to |
| 1357 |
indicate that the subroutine is a dynamic filter factory. |
| 1358 |
|
| 1359 |
Returns a true value or throws a 'C<filter>' exception on error. |
| 1360 |
|
| 1361 |
=head2 define_view($name, \%params) |
| 1362 |
|
| 1363 |
This method allows you to define a named L<view|Template::View>. |
| 1364 |
|
| 1365 |
$context->define_view( |
| 1366 |
my_view => { |
| 1367 |
prefix => 'my_templates/' |
| 1368 |
} |
| 1369 |
); |
| 1370 |
|
| 1371 |
The view is then accessible as a template variable. |
| 1372 |
|
| 1373 |
[% my_view.print(some_data) %] |
| 1374 |
|
| 1375 |
=head2 define_views($views) |
| 1376 |
|
| 1377 |
This method allows you to define multiple named L<views|Template::View>. |
| 1378 |
A reference to a hash array or list reference should be passed as an argument. |
| 1379 |
|
| 1380 |
$context->define_view({ # hash reference |
| 1381 |
my_view_one => { |
| 1382 |
prefix => 'my_templates_one/' |
| 1383 |
}, |
| 1384 |
my_view_two => { |
| 1385 |
prefix => 'my_templates_two/' |
| 1386 |
} |
| 1387 |
}); |
| 1388 |
|
| 1389 |
If you're defining multiple views of which one or more are based on other |
| 1390 |
views in the same definition then you should pass them as a list reference. |
| 1391 |
This ensures that they get created in the right order (Perl does not preserve |
| 1392 |
the order of items defined in a hash reference so you can't guarantee that |
| 1393 |
your base class view will be defined before your subclass view). |
| 1394 |
|
| 1395 |
$context->define_view([ # list referenence |
| 1396 |
my_view_one => { |
| 1397 |
prefix => 'my_templates_one/' |
| 1398 |
}, |
| 1399 |
my_view_two => { |
| 1400 |
prefix => 'my_templates_two/' , |
| 1401 |
base => 'my_view_one', |
| 1402 |
} |
| 1403 |
]); |
| 1404 |
|
| 1405 |
The views are then accessible as template variables. |
| 1406 |
|
| 1407 |
[% my_view_one.print(some_data) %] |
| 1408 |
[% my_view_two.print(some_data) %] |
| 1409 |
|
| 1410 |
See also the L<VIEWS> option. |
| 1411 |
|
| 1412 |
=head2 localise(\%vars) |
| 1413 |
|
| 1414 |
Clones the stash to create a context with localised variables. Returns a |
| 1415 |
reference to the newly cloned stash object which is also stored |
| 1416 |
internally. |
| 1417 |
|
| 1418 |
$stash = $context->localise(); |
| 1419 |
|
| 1420 |
=head2 delocalise() |
| 1421 |
|
| 1422 |
Restore the stash to its state prior to localisation. |
| 1423 |
|
| 1424 |
$stash = $context->delocalise(); |
| 1425 |
|
| 1426 |
=head2 visit(\%blocks) |
| 1427 |
|
| 1428 |
This method is called by L<Template::Document> objects immediately before |
| 1429 |
they process their content. It is called to register any local C<BLOCK> |
| 1430 |
definitions with the context object so that they may be subsequently |
| 1431 |
delivered on request. |
| 1432 |
|
| 1433 |
=head2 leave() |
| 1434 |
|
| 1435 |
Compliment to the L<visit()> method. Called by L<Template::Document> objects |
| 1436 |
immediately after they process their content. |
| 1437 |
|
| 1438 |
=head2 reset() |
| 1439 |
|
| 1440 |
Clears the local L<BLOCKS> cache of any C<BLOCK> definitions. Any initial set of |
| 1441 |
L<BLOCKS> specified as a configuration item to the constructor will be reinstated. |
| 1442 |
|
| 1443 |
=head2 AUTOLOAD |
| 1444 |
|
| 1445 |
An C<AUTOLOAD> method provides access to context configuration items. |
| 1446 |
|
| 1447 |
$stash = $context->stash(); |
| 1448 |
$tflag = $context->trim(); |
| 1449 |
$epflag = $context->eval_perl(); |
| 1450 |
... |
| 1451 |
|
| 1452 |
=head1 AUTHOR |
| 1453 |
|
| 1454 |
Andy Wardley E<lt>[email protected]<gt> L<http://wardley.org/> |
| 1455 |
|
| 1456 |
=head1 COPYRIGHT |
| 1457 |
|
| 1458 |
Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved. |
| 1459 |
|
| 1460 |
This module is free software; you can redistribute it and/or |
| 1461 |
modify it under the same terms as Perl itself. |
| 1462 |
|
| 1463 |
=head1 SEE ALSO |
| 1464 |
|
| 1465 |
L<Template>, L<Template::Document>, L<Template::Exception>, |
| 1466 |
L<Template::Filters>, L<Template::Plugins>, L<Template::Provider>, |
| 1467 |
L<Template::Service>, L<Template::Stash> |
| 1468 |
|
| 1469 |
=cut |
| 1470 |
|
| 1471 |
# Local Variables: |
| 1472 |
# mode: perl |
| 1473 |
# perl-indent-level: 4 |
| 1474 |
# indent-tabs-mode: nil |
| 1475 |
# End: |
| 1476 |
# |
| 1477 |
# vim: expandtab shiftwidth=4: |