1 package Catalyst::View::TT;
4 use base qw/Catalyst::View/;
11 __PACKAGE__->mk_accessors('template');
12 __PACKAGE__->mk_accessors('include_path');
16 Catalyst::View::TT - Template View Class
20 # use the helper to create View
21 myapp_create.pl view TT TT
23 # configure in lib/MyApp.pm
27 root => MyApp->path_to('root');,
29 # any TT configurations items go here
31 MyApp->path_to( 'root', 'src' ),
32 MyApp->path_to( 'root', 'lib' ),
34 PRE_PROCESS => 'config/main',
35 WRAPPER => 'site/wrapper',
36 TEMPLATE_EXTENSION => '.tt',
38 # two optional config items
39 CATALYST_VAR => 'Catalyst',
44 # render view from lib/MyApp.pm or lib/MyApp::C::SomeController.pm
46 sub message : Global {
47 my ( $self, $c ) = @_;
48 $c->stash->{template} = 'message.tt2';
49 $c->stash->{message} = 'Hello World!';
50 $c->forward('MyApp::V::TT');
53 # access variables from template
55 The message is: [% message %].
57 # example when CATALYST_VAR is set to 'Catalyst'
58 Context is [% Catalyst %]
59 The base is [% Catalyst.req.base %]
60 The name is [% Catalyst.config.name %]
62 # example when CATALYST_VAR isn't set
64 The base is [% base %]
65 The name is [% name %]
69 This is the Catalyst view class for the L<Template Toolkit|Template>.
70 Your application should defined a view class which is a subclass of
71 this module. The easiest way to achieve this is using the
72 F<myapp_create.pl> script (where F<myapp> should be replaced with
73 whatever your application is called). This script is created as part
74 of the Catalyst setup.
76 $ script/myapp_create.pl view TT TT
78 This creates a MyApp::V::TT.pm module in the F<lib> directory (again,
79 replacing C<MyApp> with the name of your application) which looks
82 package FooBar::V::TT;
85 use base 'Catalyst::View::TT';
87 __PACKAGE__->config->{DEBUG} = 'all';
89 Now you can modify your action handlers in the main application and/or
90 controllers to forward to your view class. You might choose to do this
91 in the end() method, for example, to automatically forward all actions
94 # In MyApp or MyApp::Controller::SomeController
98 $c->forward('MyApp::V::TT');
103 There are a three different ways to configure your view class. The
104 first way is to call the C<config()> method in the view subclass. This
105 happens when the module is first loaded.
107 package MyApp::V::TT;
110 use base 'Catalyst::View::TT';
112 MyApp::V::TT->config({
114 MyApp->path_to( 'root', 'templates', 'lib' ),
115 MyApp->path_to( 'root', 'templates', 'src' ),
117 PRE_PROCESS => 'config/main',
118 WRAPPER => 'site/wrapper',
121 The second way is to define a C<new()> method in your view subclass.
122 This performs the configuration when the view object is created,
123 shortly after being loaded. Remember to delegate to the base class
124 C<new()> method (via C<$self-E<gt>NEXT::new()> in the example below) after
125 performing any configuration.
131 MyApp->path_to( 'root', 'templates', 'lib' ),
132 MyApp->path_to( 'root', 'templates', 'src' ),
134 PRE_PROCESS => 'config/main',
135 WRAPPER => 'site/wrapper',
137 return $self->NEXT::new(@_);
140 The final, and perhaps most direct way, is to define a class
141 item in your main application configuration, again by calling the
142 uniquitous C<config()> method. The items in the class hash are
143 added to those already defined by the above two methods. This happens
144 in the base class new() method (which is one reason why you must
145 remember to call it via C<NEXT> if you redefine the C<new()> method in a
155 root => MyApp->path_to('root'),
158 MyApp->path_to( 'root', 'templates', 'lib' ),
159 MyApp->path_to( 'root', 'templates', 'src' ),
161 PRE_PROCESS => 'config/main',
162 WRAPPER => 'site/wrapper',
166 Note that any configuration items defined by one of the earlier
167 methods will be overwritten by items of the same name provided by the
170 =head2 DYNAMIC INCLUDE_PATH
172 Sometimes it is desirable to modify INCLUDE_PATH for your templates at run time.
174 Additional paths can be added to the start of INCLUDE_PATH via the stash as
177 $c->stash->{additional_template_paths} =
178 [$c->config->{root} . '/test_include_path'];
180 If you need to add paths to the end of INCLUDE_PATH, there is also an
181 include_path() accessor available:
183 push( @{ $c->view('TT')->include_path }, qw/path/ );
185 Note that if you use include_path() to add extra paths to INCLUDE_PATH, you
186 MUST check for duplicate paths. Without such checking, the above code will add
187 "path" to INCLUDE_PATH at every request, causing a memory leak.
189 A safer approach is to use include_path() to overwrite the array of paths
190 rather than adding to it. This eliminates both the need to perform duplicate
191 checking and the chance of a memory leak:
193 @{ $c->view('TT')->include_path } = qw/path another_path/;
195 If you are calling C<render> directly then you can specify dynamic paths by
196 having a C<additional_include_paths> key with a value of additonal directories
197 to search. See L<CAPTURING TEMPLATE OUTPUT> for an example showing this.
199 =head2 RENDERING VIEWS
201 The view plugin renders the template specified in the C<template>
204 sub message : Global {
205 my ( $self, $c ) = @_;
206 $c->stash->{template} = 'message.tt2';
207 $c->forward('MyApp::V::TT');
210 If a class item isn't defined, then it instead uses the
211 current match, as returned by C<< $c->match >>. In the above
212 example, this would be C<message>.
214 The items defined in the stash are passed to the Template Toolkit for
215 use as template variables.
217 sub default : Private {
218 my ( $self, $c ) = @_;
219 $c->stash->{template} = 'message.tt2';
220 $c->stash->{message} = 'Hello World!';
221 $c->forward('MyApp::V::TT');
224 A number of other template variables are also added:
226 c A reference to the context object, $c
227 base The URL base, from $c->req->base()
228 name The application name, from $c->config->{ name }
230 These can be accessed from the template in the usual way:
234 The message is: [% message %]
235 The base is [% base %]
236 The name is [% name %]
239 The output generated by the template is stored in C<< $c->response->body >>.
241 =head2 CAPTURING TEMPLATE OUTPUT
243 If you wish to use the output of a template for some other purpose than
244 displaying in the response, e.g. for sending an email, this is possible using
245 L<Catalyst::Plugin::Email> and the L<render> method:
247 sub send_email : Local {
252 To => 'me@localhost',
253 Subject => 'A TT Email',
255 body => $c->view('TT')->render($c, 'email.tt', {
256 additional_include_paths => [ $c->config->{root} . '/email_templates'],
257 email_tmpl_param1 => 'foo'
261 # Redirect or display a message
264 =head2 TEMPLATE PROFILING
266 See L<C<TIMER>> property of the L<config> method.
274 The constructor for the TT view. Sets up the template provider,
275 and reads the application config.
280 my ( $paths, $dlim ) = shift;
281 return () if ( !$paths );
282 return @{$paths} if ( ref $paths eq 'ARRAY' );
284 # tweak delim to ignore C:/
285 unless ( defined $dlim ) {
286 $dlim = ( $^O eq 'MSWin32' ) ? ':(?!\\/)' : ':';
288 return split( /$dlim/, $paths );
292 my ( $class, $c, $arguments ) = @_;
295 TEMPLATE_EXTENSION => '',
299 if ( !( ref $config->{INCLUDE_PATH} eq 'ARRAY' ) ) {
300 my $delim = $config->{DELIMITER};
301 my @include_path = _coerce_paths( $config->{INCLUDE_PATH}, $delim );
302 if ( !@include_path ) {
303 my $root = $c->config->{root};
304 my $base = Path::Class::dir( $root, 'base' );
305 @include_path = ( "$root", "$base" );
307 $config->{INCLUDE_PATH} = \@include_path;
310 # if we're debugging and/or the TIMER option is set, then we install
311 # Template::Timer as a custom CONTEXT object, but only if we haven't
312 # already got a custom CONTEXT defined
314 if ( $config->{TIMER} ) {
315 if ( $config->{CONTEXT} ) {
317 'Cannot use Template::Timer - a TT CONTEXT is already defined'
321 $config->{CONTEXT} = Template::Timer->new(%$config);
325 if ( $c->debug && $config->{DUMP_CONFIG} ) {
327 $c->log->debug( "TT Config: ", Dumper($config) );
329 if ( $config->{PROVIDERS} ) {
331 if ( ref( $config->{PROVIDERS} ) eq 'ARRAY' ) {
332 foreach my $p ( @{ $config->{PROVIDERS} } ) {
333 my $pname = $p->{name};
334 eval "require Template::Provider::$pname";
337 "Template::Provider::${pname}"->new( $p->{args} );
341 delete $config->{PROVIDERS};
343 $config->{LOAD_TEMPLATES} = \@providers;
347 my $self = $class->NEXT::new(
350 template => Template->new($config) || do {
351 my $error = Template->error();
352 $c->log->error($error);
359 $self->include_path( $config->{INCLUDE_PATH} );
360 $self->config($config);
367 Renders the template specified in C<< $c->stash->{template} >> or
368 C<< $c->action >> (the private name of the matched action. Calls L<render> to
369 perform actual rendering. Output is stored in C<< $c->response->body >>.
374 my ( $self, $c ) = @_;
376 my $template = $c->stash->{template}
377 || $c->action . $self->config->{TEMPLATE_EXTENSION};
380 $c->log->debug('No template specified for rendering') if $c->debug;
384 my $output = $self->render( $c, $template );
386 if ( (Scalar::Util::blessed($output)||'') eq 'Template::Exception' ) {
387 my $error = qq/Coldn't render template "$output"/;
388 $c->log->error($error);
393 unless ( $c->response->content_type ) {
394 $c->response->content_type('text/html; charset=utf-8');
397 $c->response->body($output);
402 =item render($c, $template, \%args)
404 Renders the given template and returns output, or a L<Template::Exception>
407 The template variables are set to C<%$args> if $args is a hashref, or
408 $C<< $c->stash >> otherwise. In either case the variables are augmented with
409 C<base> set to C< << $c->req->base >>, C<c> to C<$c> and C<name> to
410 C<< $c->config->{name} >>. Alternately, the C<CATALYST_VAR> configuration item
411 can be defined to specify the name of a template variable through which the
412 context reference (C<$c>) can be accessed. In this case, the C<c>, C<base> and
413 C<name> variables are omitted.
415 C<$template> can be anything that Template::process understands how to
416 process, including the name of a template file or a reference to a test string.
417 See L<Template::process|Template/process> for a full list of supported formats.
422 my ( $self, $c, $template, $args ) = @_;
424 $c->log->debug(qq/Rendering template "$template"/) if $c->debug;
428 ( ref $args eq 'HASH' ? %$args : %{ $c->stash() } ),
429 $self->template_vars($c)
432 local $self->{include_path} = $self->include_path;
433 unshift @{ $self->{include_path} }, @{ $vars->{additional_template_paths} }
434 if ref $c->stash->{additional_template_paths};
436 unless ( $self->template->process( $template, $vars, \$output ) ) {
437 return $self->template->error;
446 Returns a list of keys/values to be used as the catalyst variables in the
452 my ( $self, $c ) = @_;
454 my $cvar = $self->config->{CATALYST_VAR};
460 base => $c->req->base,
461 name => $c->config->{name}
467 This method allows your view subclass to pass additional settings to
468 the TT configuration hash, or to set the options as below:
472 =item C<CATALYST_VAR>
474 Allows you to change the name of the Catalyst context object. If set, it will also
475 remove the base and name aliases, so you will have access them through <context>.
481 root => MyApp->path_to('root'),
483 CATALYST_VAR => 'Catalyst',
489 The base is [% Catalyst.req.base %]
490 The name is [% Catalyst.config.name %]
494 If you have configured Catalyst for debug output, and turned on the TIMER setting,
495 C<Catalyst::View::TT> will enable profiling of template processing
496 (using L<Template::Timer>). This will embed HTML comments in the
497 output from your templates, such as:
499 <!-- TIMER START: process mainmenu/mainmenu.ttml -->
500 <!-- TIMER START: include mainmenu/cssindex.tt -->
501 <!-- TIMER START: process mainmenu/cssindex.tt -->
502 <!-- TIMER END: process mainmenu/cssindex.tt (0.017279 seconds) -->
503 <!-- TIMER END: include mainmenu/cssindex.tt (0.017401 seconds) -->
507 <!-- TIMER END: process mainmenu/footer.tt (0.003016 seconds) -->
510 =item C<TEMPLATE_EXTENSION>
512 a sufix to add when looking for templates bases on the C<match> method in L<Catalyst::Request>.
516 package MyApp::C::Test;
517 sub test : Local { .. }
519 Would by default look for a template in <root>/test/test. If you set TEMPLATE_EXTENSION to '.tt', it will look for
528 The L<Catalyst::Helper::View::TT> and
529 L<Catalyst::Helper::View::TTSite> helper modules are provided to create
530 your view module. There are invoked by the F<myapp_create.pl> script:
532 $ script/myapp_create.pl view TT TT
534 $ script/myapp_create.pl view TT TTSite
536 The L<Catalyst::Helper::View::TT> module creates a basic TT view
537 module. The L<Catalyst::Helper::View::TTSite> module goes a little
538 further. It also creates a default set of templates to get you
539 started. It also configures the view module to locate the templates
544 L<Catalyst>, L<Catalyst::Helper::View::TT>,
545 L<Catalyst::Helper::View::TTSite>, L<Template::Manual>
549 Sebastian Riedel, C<sri@cpan.org>
551 Marcus Ramberg, C<mramberg@cpan.org>
553 Jesse Sheidlower, C<jester@panix.com>
555 Andy Wardley, C<abw@cpan.org>
559 This program is free software, you can redistribute it and/or modify it
560 under the same terms as Perl itself.