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