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