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