1 package Catalyst::View::TT;
4 use base qw/Catalyst::View/;
10 our $VERSION = '0.29';
12 __PACKAGE__->mk_accessors('template');
13 __PACKAGE__->mk_accessors('include_path');
15 *paths = \&include_path;
19 Catalyst::View::TT - Template View Class
23 # use the helper to create your View
24 myapp_create.pl view TT TT
26 # configure in lib/MyApp.pm (Could be set from configfile instead)
30 root => MyApp->path_to('root'),
32 # any TT configurations items go here
34 MyApp->path_to( 'root', 'src' ),
35 MyApp->path_to( 'root', 'lib' ),
37 TEMPLATE_EXTENSION => '.tt',
41 PRE_PROCESS => 'config/main',
42 WRAPPER => 'site/wrapper',
46 # render view from lib/MyApp.pm or lib/MyApp::C::SomeController.pm
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');
55 # access variables from template
57 The message is: [% message %].
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 %]
64 # example when CATALYST_VAR isn't set
66 The base is [% base %]
67 The name is [% name %]
72 my ( $paths, $dlim ) = shift;
73 return () if ( !$paths );
74 return @{$paths} if ( ref $paths eq 'ARRAY' );
76 # tweak delim to ignore C:/
77 unless ( defined $dlim ) {
78 $dlim = ( $^O eq 'MSWin32' ) ? ':(?!\\/)' : ':';
80 return split( /$dlim/, $paths );
84 my ( $class, $c, $arguments ) = @_;
87 TEMPLATE_EXTENSION => '',
91 if ( ! (ref $config->{INCLUDE_PATH} eq 'ARRAY') ) {
92 my $delim = $config->{DELIMITER};
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" );
100 $config->{INCLUDE_PATH} = \@include_path;
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
107 if ( $config->{TIMER} ) {
108 if ( $config->{CONTEXT} ) {
110 'Cannot use Template::Timer - a TT CONTEXT is already defined'
114 $config->{CONTEXT} = Template::Timer->new(%$config);
118 if ( $c->debug && $config->{DUMP_CONFIG} ) {
119 $c->log->debug( "TT Config: ", dump($config) );
122 my $self = $class->next::method(
126 # Set base include paths. Local'd in render if needed
127 $self->include_path($config->{INCLUDE_PATH});
129 $self->config($config);
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.
135 # Use a weakend copy of self so we dont have loops preventing GC from working
137 Scalar::Util::weaken($copy);
138 $config->{INCLUDE_PATH} = [ sub { $copy->paths } ];
140 if ( $config->{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_')
148 $p->{args} = { %$config };
152 if($pname =~ s/^\+//) {
159 # We copy the args people want from the config
162 if ($p->{copy_config}) {
163 map { $p->{args}->{$_} = $config->{$_} }
164 grep { exists $config->{$_} }
165 @{ $p->{copy_config} };
168 eval "require $prov";
170 push @providers, "$prov"->new($p->{args});
174 $c->log->warn("Can't load $prov, ($@)");
178 delete $config->{PROVIDERS};
180 $config->{LOAD_TEMPLATES} = \@providers;
185 Template->new($config) || do {
186 my $error = Template->error();
187 $c->log->error($error);
197 my ( $self, $c ) = @_;
199 my $template = $c->stash->{template}
200 || $c->action . $self->config->{TEMPLATE_EXTENSION};
202 unless (defined $template) {
203 $c->log->debug('No template specified for rendering') if $c->debug;
207 my $output = $self->render($c, $template);
209 if (UNIVERSAL::isa($output, 'Template::Exception')) {
210 my $error = qq/Couldn't render template "$output"/;
211 $c->log->error($error);
216 unless ( $c->response->content_type ) {
217 $c->response->content_type('text/html; charset=utf-8');
220 $c->response->body($output);
226 my ($self, $c, $template, $args) = @_;
228 $c->log->debug(qq/Rendering template "$template"/) if $c->debug;
232 (ref $args eq 'HASH' ? %$args : %{ $c->stash() }),
233 $self->template_vars($c)
236 local $self->{include_path} =
237 [ @{ $vars->{additional_template_paths} }, @{ $self->{include_path} } ]
238 if ref $vars->{additional_template_paths};
240 unless ($self->template->process( $template, $vars, \$output ) ) {
241 return $self->template->error;
248 my ( $self, $c ) = @_;
250 my $cvar = $self->config->{CATALYST_VAR};
256 base => $c->req->base,
257 name => $c->config->{name}
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.
275 $ script/myapp_create.pl view TT TT
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
281 package FooBar::V::TT;
284 use base 'Catalyst::View::TT';
286 __PACKAGE__->config->{DEBUG} = 'all';
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.
293 # In MyApp or MyApp::Controller::SomeController
296 my( $self, $c ) = @_;
297 $c->forward('MyApp::V::TT');
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.
306 package MyApp::V::TT;
309 use base 'Catalyst::View::TT';
311 MyApp::V::TT->config({
313 MyApp->path_to( 'root', 'templates', 'lib' ),
314 MyApp->path_to( 'root', 'templates', 'src' ),
316 PRE_PROCESS => 'config/main',
317 WRAPPER => 'site/wrapper',
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.
330 MyApp->path_to( 'root', 'templates', 'lib' ),
331 MyApp->path_to( 'root', 'templates', 'src' ),
333 PRE_PROCESS => 'config/main',
334 WRAPPER => 'site/wrapper',
336 return $self->next::method(@_);
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).
354 root => MyApp->path_to('root'),
357 MyApp->path_to( 'root', 'templates', 'lib' ),
358 MyApp->path_to( 'root', 'templates', 'src' ),
360 PRE_PROCESS => 'config/main',
361 WRAPPER => 'site/wrapper',
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
369 =head2 DYNAMIC INCLUDE_PATH
371 Sometimes it is desirable to modify INCLUDE_PATH for your templates at run time.
373 Additional paths can be added to the start of INCLUDE_PATH via the stash as
376 $c->stash->{additional_template_paths} =
377 [$c->config->{root} . '/test_include_path'];
379 If you need to add paths to the end of INCLUDE_PATH, there is also an
380 include_path() accessor available:
382 push( @{ $c->view('TT')->include_path }, qw/path/ );
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.
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:
392 @{ $c->view('TT')->include_path } = qw/path another_path/;
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.
398 =head2 RENDERING VIEWS
400 The view plugin renders the template specified in the C<template>
403 sub message : Global {
404 my ( $self, $c ) = @_;
405 $c->stash->{template} = 'message.tt2';
406 $c->forward('MyApp::V::TT');
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>.
414 The items defined in the stash are passed to the Template Toolkit for
415 use as template variables.
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');
424 A number of other template variables are also added:
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 }
430 These can be accessed from the template in the usual way:
434 The message is: [% message %]
435 The base is [% base %]
436 The name is [% name %]
439 The output generated by the template is stored in C<< $c->response->body >>.
441 =head2 CAPTURING TEMPLATE OUTPUT
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:
447 sub send_email : Local {
452 To => 'me@localhost',
453 Subject => 'A TT Email',
455 body => $c->view('TT')->render($c, 'email.tt', {
456 additional_template_paths => [ $c->config->{root} . '/email_templates'],
457 email_tmpl_param1 => 'foo'
461 # Redirect or display a message
464 =head2 TEMPLATE PROFILING
466 See L<C<TIMER>> property of the L<config> method.
472 The constructor for the TT view. Sets up the template provider,
473 and reads the application config.
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 >>.
481 =head2 render($c, $template, \%args)
483 Renders the given template and returns output, or a L<Template::Exception>
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.
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.
500 Returns a list of keys/values to be used as the catalyst variables in the
505 This method allows your view subclass to pass additional settings to
506 the TT configuration hash, or to set the options as below:
510 The list of paths TT will look for templates in.
512 =head2 C<CATALYST_VAR>
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>.
521 root => MyApp->path_to('root'),
523 CATALYST_VAR => 'Catalyst',
529 The base is [% Catalyst.req.base %]
530 The name is [% Catalyst.config.name %]
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:
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) -->
547 <!-- TIMER END: process mainmenu/footer.tt (0.003016 seconds) -->
550 =head2 C<TEMPLATE_EXTENSION>
552 a sufix to add when looking for templates bases on the C<match> method in L<Catalyst::Request>.
556 package MyApp::C::Test;
557 sub test : Local { .. }
559 Would by default look for a template in <root>/test/test. If you set TEMPLATE_EXTENSION to '.tt', it will look for
564 Allows you to specify the template providers that TT will use.
568 root => MyApp->path_to('root'),
574 DBI_DSN => 'dbi:DB2:books',
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
591 name => '+MyApp::Provider::Foo'
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:
596 DEFAULT_ENCODING => 'utf-8',
600 copy_config => [qw(DEFAULT_ENCODING INCLUDE_PATH)]
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
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:
613 $ script/myapp_create.pl view TT TT
615 $ script/myapp_create.pl view TT TTSite
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
625 L<Catalyst>, L<Catalyst::Helper::View::TT>,
626 L<Catalyst::Helper::View::TTSite>, L<Template::Manual>
630 Sebastian Riedel, C<sri@cpan.org>
632 Marcus Ramberg, C<mramberg@cpan.org>
634 Jesse Sheidlower, C<jester@panix.com>
636 Andy Wardley, C<abw@cpan.org>
640 This program is free software, you can redistribute it and/or modify it
641 under the same terms as Perl itself.