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