Add fully-qualified provider classname support to View::TT
[catagits/Catalyst-View-TT.git] / lib / Catalyst / View / TT.pm
CommitLineData
8077080c 1package Catalyst::View::TT;
2
3use strict;
7d8aa5ec 4use base qw/Catalyst::View/;
9e739e1e 5use Data::Dump 'dump';
8077080c 6use Template;
7use Template::Timer;
8use NEXT;
9
b63ddd04 10our $VERSION = '0.26';
8077080c 11
12__PACKAGE__->mk_accessors('template');
e2bbd784 13__PACKAGE__->mk_accessors('include_path');
8077080c 14
9d574573 15*paths = \&include_path;
16
8077080c 17=head1 NAME
18
19Catalyst::View::TT - Template View Class
20
21=head1 SYNOPSIS
22
bd4ee63a 23# use the helper to create your View
722fede4 24 myapp_create.pl view TT TT
8077080c 25
8cd017a8 26# configure in lib/MyApp.pm
27
ae035767 28 MyApp->config(
8cd017a8 29 name => 'MyApp',
e1c15a53 30 root => MyApp->path_to('root'),
ae035767 31 'View::TT' => {
8cd017a8 32 # any TT configurations items go here
33 INCLUDE_PATH => [
93f25382 34 MyApp->path_to( 'root', 'src' ),
35 MyApp->path_to( 'root', 'lib' ),
8cd017a8 36 ],
07571b2f 37 PRE_PROCESS => 'config/main',
38 WRAPPER => 'site/wrapper',
39 TEMPLATE_EXTENSION => '.tt',
8cd017a8 40
41 # two optional config items
42 CATALYST_VAR => 'Catalyst',
43 TIMER => 1,
44 },
ae035767 45 );
8cd017a8 46
47# render view from lib/MyApp.pm or lib/MyApp::C::SomeController.pm
48
49 sub message : Global {
94b3529a 50 my ( $self, $c ) = @_;
51 $c->stash->{template} = 'message.tt2';
52 $c->stash->{message} = 'Hello World!';
8cd017a8 53 $c->forward('MyApp::V::TT');
54 }
8077080c 55
8cd017a8 56# access variables from template
57
58 The message is: [% message %].
59
60 # example when CATALYST_VAR is set to 'Catalyst'
61 Context is [% Catalyst %]
62 The base is [% Catalyst.req.base %]
63 The name is [% Catalyst.config.name %]
64
65 # example when CATALYST_VAR isn't set
66 Context is [% c %]
67 The base is [% base %]
68 The name is [% name %]
69
bd4ee63a 70=cut
71
72sub _coerce_paths {
73 my ( $paths, $dlim ) = shift;
74 return () if ( !$paths );
75 return @{$paths} if ( ref $paths eq 'ARRAY' );
76
77 # tweak delim to ignore C:/
78 unless ( defined $dlim ) {
79 $dlim = ( $^O eq 'MSWin32' ) ? ':(?!\\/)' : ':';
80 }
81 return split( /$dlim/, $paths );
82}
83
84sub new {
85 my ( $class, $c, $arguments ) = @_;
86 my $config = {
87 EVAL_PERL => 0,
88 TEMPLATE_EXTENSION => '',
89 %{ $class->config },
90 %{$arguments},
91 };
92 if ( ! (ref $config->{INCLUDE_PATH} eq 'ARRAY') ) {
93 my $delim = $config->{DELIMITER};
94 my @include_path
95 = _coerce_paths( $config->{INCLUDE_PATH}, $delim );
96 if ( !@include_path ) {
97 my $root = $c->config->{root};
98 my $base = Path::Class::dir( $root, 'base' );
99 @include_path = ( "$root", "$base" );
100 }
101 $config->{INCLUDE_PATH} = \@include_path;
102 }
103
104 # if we're debugging and/or the TIMER option is set, then we install
105 # Template::Timer as a custom CONTEXT object, but only if we haven't
106 # already got a custom CONTEXT defined
107
108 if ( $config->{TIMER} ) {
109 if ( $config->{CONTEXT} ) {
110 $c->log->error(
111 'Cannot use Template::Timer - a TT CONTEXT is already defined'
112 );
113 }
114 else {
115 $config->{CONTEXT} = Template::Timer->new(%$config);
116 }
117 }
118
119 if ( $c->debug && $config->{DUMP_CONFIG} ) {
9e739e1e 120 $c->log->debug( "TT Config: ", dump($config) );
bd4ee63a 121 }
122 if ( $config->{PROVIDERS} ) {
123 my @providers = ();
124 if ( ref($config->{PROVIDERS}) eq 'ARRAY') {
125 foreach my $p (@{$config->{PROVIDERS}}) {
126 my $pname = $p->{name};
127 my $prov = 'Template::Provider';
128 if($pname eq '_file_')
129 {
130 $p->{args} = { %$config };
131 }
132 else
133 {
51199593 134 if($pname =~ s/^\+//) {
135 $prov = $pname;
136 }
137 else
138 {
139 $prov .= "::$pname";
140 }
bd4ee63a 141 }
142 eval "require $prov";
143 if(!$@) {
144 push @providers, "$prov"->new($p->{args});
145 }
146 else
147 {
148 $c->log->warn("Can't load $prov, ($@)");
149 }
150 }
151 }
152 delete $config->{PROVIDERS};
153 if(@providers) {
154 $config->{LOAD_TEMPLATES} = \@providers;
155 }
156 }
157
158 my $self = $class->NEXT::new(
159 $c, { %$config },
160 );
161
162 # Set base include paths. Local'd in render if needed
163 $self->include_path($config->{INCLUDE_PATH});
164
165 $self->config($config);
166
167 # Creation of template outside of call to new so that we can pass [ $self ]
168 # as INCLUDE_PATH config item, which then gets ->paths() called to get list
169 # of include paths to search for templates.
170
171 # Use a weakend copy of self so we dont have loops preventing GC from working
172 my $copy = $self;
173 Scalar::Util::weaken($copy);
174 $config->{INCLUDE_PATH} = [ sub { $copy->paths } ];
175
176 $self->{template} =
177 Template->new($config) || do {
178 my $error = Template->error();
179 $c->log->error($error);
180 $c->error($error);
181 return undef;
182 };
183
184
185 return $self;
186}
187
188sub process {
189 my ( $self, $c ) = @_;
190
191 my $template = $c->stash->{template}
192 || $c->action . $self->config->{TEMPLATE_EXTENSION};
193
194 unless (defined $template) {
195 $c->log->debug('No template specified for rendering') if $c->debug;
196 return 0;
197 }
198
199 my $output = $self->render($c, $template);
200
201 if (UNIVERSAL::isa($output, 'Template::Exception')) {
82b741a3 202 my $error = qq/Couldn't render template "$output"/;
bd4ee63a 203 $c->log->error($error);
204 $c->error($error);
205 return 0;
206 }
207
208 unless ( $c->response->content_type ) {
209 $c->response->content_type('text/html; charset=utf-8');
210 }
211
212 $c->response->body($output);
213
214 return 1;
215}
216
217sub render {
218 my ($self, $c, $template, $args) = @_;
219
220 $c->log->debug(qq/Rendering template "$template"/) if $c->debug;
221
222 my $output;
223 my $vars = {
224 (ref $args eq 'HASH' ? %$args : %{ $c->stash() }),
225 $self->template_vars($c)
226 };
227
228 local $self->{include_path} =
229 [ @{ $vars->{additional_template_paths} }, @{ $self->{include_path} } ]
230 if ref $vars->{additional_template_paths};
231
232 unless ($self->template->process( $template, $vars, \$output ) ) {
233 return $self->template->error;
234 } else {
235 return $output;
236 }
237}
238
239sub template_vars {
240 my ( $self, $c ) = @_;
241
242 my $cvar = $self->config->{CATALYST_VAR};
243
244 defined $cvar
245 ? ( $cvar => $c )
246 : (
247 c => $c,
248 base => $c->req->base,
249 name => $c->config->{name}
250 )
251}
252
253
2541;
255
256__END__
257
8cd017a8 258=head1 DESCRIPTION
259
260This is the Catalyst view class for the L<Template Toolkit|Template>.
261Your application should defined a view class which is a subclass of
262this module. The easiest way to achieve this is using the
263F<myapp_create.pl> script (where F<myapp> should be replaced with
264whatever your application is called). This script is created as part
265of the Catalyst setup.
266
267 $ script/myapp_create.pl view TT TT
268
269This creates a MyApp::V::TT.pm module in the F<lib> directory (again,
270replacing C<MyApp> with the name of your application) which looks
271something like this:
272
273 package FooBar::V::TT;
274
275 use strict;
276 use base 'Catalyst::View::TT';
8077080c 277
278 __PACKAGE__->config->{DEBUG} = 'all';
279
8cd017a8 280Now you can modify your action handlers in the main application and/or
281controllers to forward to your view class. You might choose to do this
282in the end() method, for example, to automatically forward all actions
283to the TT view class.
722fede4 284
8cd017a8 285 # In MyApp or MyApp::Controller::SomeController
8077080c 286
8cd017a8 287 sub end : Private {
94b3529a 288 my( $self, $c ) = @_;
8cd017a8 289 $c->forward('MyApp::V::TT');
290 }
8077080c 291
8cd017a8 292=head2 CONFIGURATION
4687ac0d 293
8cd017a8 294There are a three different ways to configure your view class. The
295first way is to call the C<config()> method in the view subclass. This
296happens when the module is first loaded.
8077080c 297
8cd017a8 298 package MyApp::V::TT;
299
300 use strict;
301 use base 'Catalyst::View::TT';
722fede4 302
8cd017a8 303 MyApp::V::TT->config({
7d8aa5ec 304 INCLUDE_PATH => [
305 MyApp->path_to( 'root', 'templates', 'lib' ),
306 MyApp->path_to( 'root', 'templates', 'src' ),
307 ],
8cd017a8 308 PRE_PROCESS => 'config/main',
309 WRAPPER => 'site/wrapper',
310 });
311
312The second way is to define a C<new()> method in your view subclass.
313This performs the configuration when the view object is created,
314shortly after being loaded. Remember to delegate to the base class
315C<new()> method (via C<$self-E<gt>NEXT::new()> in the example below) after
316performing any configuration.
317
318 sub new {
319 my $self = shift;
320 $self->config({
7d8aa5ec 321 INCLUDE_PATH => [
322 MyApp->path_to( 'root', 'templates', 'lib' ),
323 MyApp->path_to( 'root', 'templates', 'src' ),
324 ],
8cd017a8 325 PRE_PROCESS => 'config/main',
326 WRAPPER => 'site/wrapper',
327 });
328 return $self->NEXT::new(@_);
329 }
330
94b3529a 331The final, and perhaps most direct way, is to define a class
8cd017a8 332item in your main application configuration, again by calling the
94b3529a 333uniquitous C<config()> method. The items in the class hash are
8cd017a8 334added to those already defined by the above two methods. This happens
335in the base class new() method (which is one reason why you must
336remember to call it via C<NEXT> if you redefine the C<new()> method in a
337subclass).
338
339 package MyApp;
340
341 use strict;
342 use Catalyst;
343
8cd017a8 344 MyApp->config({
345 name => 'MyApp',
7d8aa5ec 346 root => MyApp->path_to('root'),
7d607671 347 'V::TT' => {
7d8aa5ec 348 INCLUDE_PATH => [
349 MyApp->path_to( 'root', 'templates', 'lib' ),
350 MyApp->path_to( 'root', 'templates', 'src' ),
351 ],
8cd017a8 352 PRE_PROCESS => 'config/main',
353 WRAPPER => 'site/wrapper',
354 },
355 });
356
357Note that any configuration items defined by one of the earlier
358methods will be overwritten by items of the same name provided by the
359latter methods.
360
e2bbd784 361=head2 DYNAMIC INCLUDE_PATH
362
f7dfca06 363Sometimes it is desirable to modify INCLUDE_PATH for your templates at run time.
364
365Additional paths can be added to the start of INCLUDE_PATH via the stash as
366follows:
367
368 $c->stash->{additional_template_paths} =
369 [$c->config->{root} . '/test_include_path'];
370
371If you need to add paths to the end of INCLUDE_PATH, there is also an
372include_path() accessor available:
373
374 push( @{ $c->view('TT')->include_path }, qw/path/ );
375
376Note that if you use include_path() to add extra paths to INCLUDE_PATH, you
377MUST check for duplicate paths. Without such checking, the above code will add
378"path" to INCLUDE_PATH at every request, causing a memory leak.
379
380A safer approach is to use include_path() to overwrite the array of paths
381rather than adding to it. This eliminates both the need to perform duplicate
382checking and the chance of a memory leak:
e2bbd784 383
f7dfca06 384 @{ $c->view('TT')->include_path } = qw/path another_path/;
e2bbd784 385
1bc9fc55 386If you are calling C<render> directly then you can specify dynamic paths by
9d574573 387having a C<additional_template_paths> key with a value of additonal directories
1bc9fc55 388to search. See L<CAPTURING TEMPLATE OUTPUT> for an example showing this.
389
8cd017a8 390=head2 RENDERING VIEWS
391
392The view plugin renders the template specified in the C<template>
393item in the stash.
394
395 sub message : Global {
94b3529a 396 my ( $self, $c ) = @_;
397 $c->stash->{template} = 'message.tt2';
8cd017a8 398 $c->forward('MyApp::V::TT');
399 }
722fede4 400
c969f23a 401If a stash item isn't defined, then it instead uses the
402stringification of the action dispatched to (as defined by $c->action)
403in the above example, this would be C<message>, but because the default
404is to append '.tt', it would load C<root/message.tt>.
8cd017a8 405
406The items defined in the stash are passed to the Template Toolkit for
407use as template variables.
408
8cd017a8 409 sub default : Private {
94b3529a 410 my ( $self, $c ) = @_;
411 $c->stash->{template} = 'message.tt2';
412 $c->stash->{message} = 'Hello World!';
8cd017a8 413 $c->forward('MyApp::V::TT');
414 }
7b592fc7 415
8cd017a8 416A number of other template variables are also added:
8077080c 417
8cd017a8 418 c A reference to the context object, $c
419 base The URL base, from $c->req->base()
420 name The application name, from $c->config->{ name }
421
422These can be accessed from the template in the usual way:
423
424<message.tt2>:
425
426 The message is: [% message %]
427 The base is [% base %]
428 The name is [% name %]
429
8cd017a8 430
1bc9fc55 431The output generated by the template is stored in C<< $c->response->body >>.
432
433=head2 CAPTURING TEMPLATE OUTPUT
434
435If you wish to use the output of a template for some other purpose than
436displaying in the response, e.g. for sending an email, this is possible using
437L<Catalyst::Plugin::Email> and the L<render> method:
438
439 sub send_email : Local {
440 my ($self, $c) = @_;
441
442 $c->email(
443 header => [
444 To => 'me@localhost',
445 Subject => 'A TT Email',
446 ],
447 body => $c->view('TT')->render($c, 'email.tt', {
9d574573 448 additional_template_paths => [ $c->config->{root} . '/email_templates'],
1bc9fc55 449 email_tmpl_param1 => 'foo'
450 }
451 ),
452 );
453 # Redirect or display a message
454 }
8cd017a8 455
456=head2 TEMPLATE PROFILING
457
1bc9fc55 458See L<C<TIMER>> property of the L<config> method.
459
caa61517 460=head2 METHODS
8077080c 461
b63ddd04 462=head2 new
2774dc77 463
464The constructor for the TT view. Sets up the template provider,
465and reads the application config.
466
b63ddd04 467=head2 process
8077080c 468
1bc9fc55 469Renders the template specified in C<< $c->stash->{template} >> or
470C<< $c->action >> (the private name of the matched action. Calls L<render> to
471perform actual rendering. Output is stored in C<< $c->response->body >>.
8077080c 472
b63ddd04 473=head2 render($c, $template, \%args)
1bc9fc55 474
475Renders the given template and returns output, or a L<Template::Exception>
476object upon error.
477
478The template variables are set to C<%$args> if $args is a hashref, or
479$C<< $c->stash >> otherwise. In either case the variables are augmented with
480C<base> set to C< << $c->req->base >>, C<c> to C<$c> and C<name> to
481C<< $c->config->{name} >>. Alternately, the C<CATALYST_VAR> configuration item
482can be defined to specify the name of a template variable through which the
483context reference (C<$c>) can be accessed. In this case, the C<c>, C<base> and
484C<name> variables are omitted.
485
486C<$template> can be anything that Template::process understands how to
487process, including the name of a template file or a reference to a test string.
488See L<Template::process|Template/process> for a full list of supported formats.
489
b63ddd04 490=head2 template_vars
850ee226 491
1bc9fc55 492Returns a list of keys/values to be used as the catalyst variables in the
850ee226 493template.
494
b63ddd04 495=head2 config
8077080c 496
8cd017a8 497This method allows your view subclass to pass additional settings to
4729c102 498the TT configuration hash, or to set the options as below:
499
b63ddd04 500=head2 paths
501
502The list of paths TT will look for templates in.
4729c102 503
b63ddd04 504=head2 C<CATALYST_VAR>
4729c102 505
506Allows you to change the name of the Catalyst context object. If set, it will also
507remove the base and name aliases, so you will have access them through <context>.
508
509For example:
510
511 MyApp->config({
512 name => 'MyApp',
7d8aa5ec 513 root => MyApp->path_to('root'),
4729c102 514 'V::TT' => {
515 CATALYST_VAR => 'Catalyst',
516 },
517 });
518
519F<message.tt2>:
520
521 The base is [% Catalyst.req.base %]
522 The name is [% Catalyst.config.name %]
523
b63ddd04 524=head2 C<TIMER>
4729c102 525
526If you have configured Catalyst for debug output, and turned on the TIMER setting,
527C<Catalyst::View::TT> will enable profiling of template processing
528(using L<Template::Timer>). This will embed HTML comments in the
529output from your templates, such as:
530
531 <!-- TIMER START: process mainmenu/mainmenu.ttml -->
532 <!-- TIMER START: include mainmenu/cssindex.tt -->
533 <!-- TIMER START: process mainmenu/cssindex.tt -->
534 <!-- TIMER END: process mainmenu/cssindex.tt (0.017279 seconds) -->
535 <!-- TIMER END: include mainmenu/cssindex.tt (0.017401 seconds) -->
536
537 ....
538
539 <!-- TIMER END: process mainmenu/footer.tt (0.003016 seconds) -->
540
541
b63ddd04 542=head2 C<TEMPLATE_EXTENSION>
4729c102 543
747f2b6d 544a sufix to add when looking for templates bases on the C<match> method in L<Catalyst::Request>.
4729c102 545
546For example:
547
548 package MyApp::C::Test;
549 sub test : Local { .. }
550
551Would by default look for a template in <root>/test/test. If you set TEMPLATE_EXTENSION to '.tt', it will look for
552<root>/test/test.tt.
553
51199593 554=head2 C<PROVIDERS>
555
556Allows you to specify the template providers that TT will use.
557
558 MyApp->config({
559 name => 'MyApp',
560 root => MyApp->path_to('root'),
561 'V::TT' => {
562 PROVIDERS => [
563 {
564 name => 'DBI',
565 args => {
566 DBI_DSN => 'dbi:DB2:books',
567 DBI_USER=> 'foo'
568 }
569 }, {
570 name => '_file_',
571 args => {}
572 }
573 ]
574 },
575 });
576
577The 'name' key should correspond to the class name of the provider you
578want to use. The _file_ name is a special case that represents the default
579TT file-based provider. By default the name is will be prefixed with
580'Template::Provider::'. You can fully qualify the name by using a unary
581plus:
582
583 name => '+MyApp::Provider::Foo'
584
8cd017a8 585=head2 HELPERS
586
587The L<Catalyst::Helper::View::TT> and
588L<Catalyst::Helper::View::TTSite> helper modules are provided to create
589your view module. There are invoked by the F<myapp_create.pl> script:
590
591 $ script/myapp_create.pl view TT TT
592
593 $ script/myapp_create.pl view TT TTSite
594
595The L<Catalyst::Helper::View::TT> module creates a basic TT view
596module. The L<Catalyst::Helper::View::TTSite> module goes a little
597further. It also creates a default set of templates to get you
598started. It also configures the view module to locate the templates
599automatically.
600
8077080c 601=head1 SEE ALSO
602
8cd017a8 603L<Catalyst>, L<Catalyst::Helper::View::TT>,
604L<Catalyst::Helper::View::TTSite>, L<Template::Manual>
8077080c 605
c0eb0527 606=head1 AUTHORS
8077080c 607
608Sebastian Riedel, C<sri@cpan.org>
c0eb0527 609
d938377b 610Marcus Ramberg, C<mramberg@cpan.org>
c0eb0527 611
722fede4 612Jesse Sheidlower, C<jester@panix.com>
c0eb0527 613
8cd017a8 614Andy Wardley, C<abw@cpan.org>
8077080c 615
616=head1 COPYRIGHT
617
2774dc77 618This program is free software, you can redistribute it and/or modify it
619under the same terms as Perl itself.
8077080c 620
621=cut