1Catalyst::View::TT(3) User Contributed Perl DocumentationCatalyst::View::TT(3)
2
3
4
6 Catalyst::View::TT - Template View Class
7
9 # use the helper to create your View
10
11 myapp_create.pl view Web TT
12
13 # add custom configuration in View/Web.pm
14
15 __PACKAGE__->config(
16 # any TT configuration items go here
17 TEMPLATE_EXTENSION => '.tt',
18 CATALYST_VAR => 'c',
19 TIMER => 0,
20 ENCODING => 'utf-8'
21 # Not set by default
22 PRE_PROCESS => 'config/main',
23 WRAPPER => 'site/wrapper',
24 render_die => 1, # Default for new apps, see render method docs
25 expose_methods => [qw/method_in_view_class/],
26 );
27
28 # add include path configuration in MyApp.pm
29
30 __PACKAGE__->config(
31 'View::Web' => {
32 INCLUDE_PATH => [
33 __PACKAGE__->path_to( 'root', 'src' ),
34 __PACKAGE__->path_to( 'root', 'lib' ),
35 ],
36 },
37 );
38
39 # render view from lib/MyApp.pm or
40 lib/MyApp::Controller::SomeController.pm
41
42 sub message : Global {
43 my ( $self, $c ) = @_;
44 $c->stash->{template} = 'message.tt2';
45 $c->stash->{message} = 'Hello World!';
46 $c->forward( $c->view('Web') );
47 }
48
49 # access variables from template
50
51 The message is: [% message %].
52
53 # example when CATALYST_VAR is set to 'Catalyst'
54 Context is [% Catalyst %]
55 The base is [% Catalyst.req.base %]
56 The name is [% Catalyst.config.name %]
57
58 # example when CATALYST_VAR isn't set
59 Context is [% c %]
60 The base is [% base %]
61 The name is [% name %]
62
64 This is the Catalyst view class for the Template Toolkit. Your
65 application should defined a view class which is a subclass of this
66 module. Throughout this manual it will be assumed that your application
67 is named MyApp and you are creating a TT view named Web; these names
68 are placeholders and should always be replaced with whatever name
69 you've chosen for your application and your view. The easiest way to
70 create a TT view class is through the myapp_create.pl script that is
71 created along with the application:
72
73 $ script/myapp_create.pl view Web TT
74
75 This creates a MyApp::View::Web.pm module in the lib directory (again,
76 replacing "MyApp" with the name of your application) which looks
77 something like this:
78
79 package FooBar::View::Web;
80 use Moose;
81
82 extends 'Catalyst::View::TT';
83
84 __PACKAGE__->config(DEBUG => 'all');
85
86 Now you can modify your action handlers in the main application and/or
87 controllers to forward to your view class. You might choose to do this
88 in the end() method, for example, to automatically forward all actions
89 to the TT view class.
90
91 # In MyApp or MyApp::Controller::SomeController
92
93 sub end : Private {
94 my( $self, $c ) = @_;
95 $c->forward( $c->view('Web') );
96 }
97
98 But if you are using the standard auto-generated end action, you don't
99 even need to do this!
100
101 # in MyApp::Controller::Root
102 sub end : ActionClass('RenderView') {} # no need to change this line
103
104 # in MyApp.pm
105 __PACKAGE__->config(
106 ...
107 default_view => 'Web',
108 );
109
110 This will Just Work. And it has the advantages that:
111
112 • If you want to use a different view for a given request, just set
113 << $c->stash->{current_view} >>. (See Catalyst's "$c->view" method
114 for details.
115
116 • << $c->res->redirect >> is handled by default. If you just forward
117 to "View::Web" in your "end" routine, you could break this by
118 sending additional content.
119
120 See Catalyst::Action::RenderView for more details.
121
122 CONFIGURATION
123 There are a three different ways to configure your view class. The
124 first way is to call the config() method in the view subclass. This
125 happens when the module is first loaded.
126
127 package MyApp::View::Web;
128 use Moose;
129 extends 'Catalyst::View::TT';
130
131 __PACKAGE__->config({
132 PRE_PROCESS => 'config/main',
133 WRAPPER => 'site/wrapper',
134 });
135
136 You may also override the configuration provided in the view class by
137 adding a 'View::Web' section to your application config.
138
139 This should generally be used to inject the include paths into the view
140 to avoid the view trying to load the application to resolve paths.
141
142 .. inside MyApp.pm ..
143 __PACKAGE__->config(
144 'View::Web' => {
145 INCLUDE_PATH => [
146 __PACKAGE__->path_to( 'root', 'templates', 'lib' ),
147 __PACKAGE__->path_to( 'root', 'templates', 'src' ),
148 ],
149 },
150 );
151
152 You can also configure your view from within your config file if you're
153 using Catalyst::Plugin::ConfigLoader. This should be reserved for
154 deployment-specific concerns. For example:
155
156 # MyApp_local.conf (Config::General format)
157
158 <View Web>
159 WRAPPER "custom_wrapper"
160 INCLUDE_PATH __path_to('root/templates/custom_site')__
161 INCLUDE_PATH __path_to('root/templates')__
162 </View>
163
164 might be used as part of a simple way to deploy different instances of
165 the same application with different themes.
166
167 DYNAMIC INCLUDE_PATH
168 Sometimes it is desirable to modify INCLUDE_PATH for your templates at
169 run time.
170
171 Additional paths can be added to the start of INCLUDE_PATH via the
172 stash as follows:
173
174 $c->stash->{additional_template_paths} =
175 [$c->config->{root} . '/test_include_path'];
176
177 If you need to add paths to the end of INCLUDE_PATH, there is also an
178 include_path() accessor available:
179
180 push( @{ $c->view('Web')->include_path }, qw/path/ );
181
182 Note that if you use include_path() to add extra paths to INCLUDE_PATH,
183 you MUST check for duplicate paths. Without such checking, the above
184 code will add "path" to INCLUDE_PATH at every request, causing a memory
185 leak.
186
187 A safer approach is to use include_path() to overwrite the array of
188 paths rather than adding to it. This eliminates both the need to
189 perform duplicate checking and the chance of a memory leak:
190
191 @{ $c->view('Web')->include_path } = qw/path another_path/;
192
193 If you are calling "render" directly then you can specify dynamic paths
194 by having a "additional_template_paths" key with a value of additional
195 directories to search. See "CAPTURING TEMPLATE OUTPUT" for an example
196 showing this.
197
198 Unicode (pre Catalyst v5.90080)
199 NOTE Starting with Catalyst v5.90080 unicode and encoding has been
200 baked into core, and the default encoding is UTF-8. The following
201 advice is for older versions of Catalyst.
202
203 Be sure to set "ENCODING => 'utf-8'" and use
204 Catalyst::Plugin::Unicode::Encoding if you want to use non-ascii
205 characters (encoded as utf-8) in your templates. This is only needed
206 if you actually have UTF8 literals in your templates and the BOM is not
207 properly set. Setting encoding here does not magically encode your
208 template output. If you are using this version of Catalyst you need to
209 all the Unicode plugin, or upgrade (preferred)
210
211 Unicode (Catalyst v5.90080+)
212 This version of Catalyst will automatically encode your body output to
213 UTF8. This means if your variables contain multibyte characters you
214 don't need top do anything else to get UTF8 output. However if your
215 templates contain UTF8 literals (like, multibyte characters actually in
216 the template text), then you do need to either set the BOM mark on the
217 template file or instruct TT to decode the templates at load time via
218 the ENCODING configuration setting. Most of the time you can just do:
219
220 MyApp::View::HTML->config(
221 ENCODING => 'UTF-8');
222
223 and that will just take care of everything. This configuration setting
224 will force Template to decode all files correctly, so that when you hit
225 the finalize_encoding step we can properly encode the body as UTF8. If
226 you fail to do this you will get double encoding issues in your output
227 (but again, only for the UTF8 literals in your actual template text.)
228
229 Again, this ENCODING configuration setting only instructs template
230 toolkit how (and if) to decode the contents of your template files when
231 reading them from disk. It has no other effect.
232
233 RENDERING VIEWS
234 The view plugin renders the template specified in the "template" item
235 in the stash.
236
237 sub message : Global {
238 my ( $self, $c ) = @_;
239 $c->stash->{template} = 'message.tt2';
240 $c->forward( $c->view('Web') );
241 }
242
243 If a stash item isn't defined, then it instead uses the stringification
244 of the action dispatched to (as defined by $c->action) in the above
245 example, this would be "message", but because the default is to append
246 '.tt', it would load "root/message.tt".
247
248 The items defined in the stash are passed to the Template Toolkit for
249 use as template variables.
250
251 sub default : Private {
252 my ( $self, $c ) = @_;
253 $c->stash->{template} = 'message.tt2';
254 $c->stash->{message} = 'Hello World!';
255 $c->forward( $c->view('Web') );
256 }
257
258 A number of other template variables are also added:
259
260 c A reference to the context object, $c
261 base The URL base, from $c->req->base()
262 name The application name, from $c->config->{ name }
263
264 These can be accessed from the template in the usual way:
265
266 <message.tt2>:
267
268 The message is: [% message %]
269 The base is [% base %]
270 The name is [% name %]
271
272 The output generated by the template is stored in "$c->response->body".
273
274 CAPTURING TEMPLATE OUTPUT
275 If you wish to use the output of a template for some other purpose than
276 displaying in the response, e.g. for sending an email, this is possible
277 using other views, such as Catalyst::View::Email::Template.
278
279 TEMPLATE PROFILING
280 See ""TIMER"" property of the "config" method.
281
283 new
284 The constructor for the TT view. Sets up the template provider, and
285 reads the application config.
286
287 process($c)
288 Renders the template specified in "$c->stash->{template}" or
289 "$c->action" (the private name of the matched action). Calls render to
290 perform actual rendering. Output is stored in "$c->response->body".
291
292 It is possible to forward to the process method of a TT view from
293 inside Catalyst like this:
294
295 $c->forward('View::Web');
296
297 N.B. This is usually done automatically by
298 Catalyst::Action::RenderView.
299
300 render($c, $template, \%args)
301 Renders the given template and returns output. Throws a
302 Template::Exception object upon error.
303
304 The template variables are set to %$args if $args is a hashref, or
305 "$c->stash" otherwise. In either case the variables are augmented with
306 "base" set to "$c->req->base", "c" to $c, and "name" to
307 "$c->config->{name}". Alternately, the "CATALYST_VAR" configuration
308 item can be defined to specify the name of a template variable through
309 which the context reference ($c) can be accessed. In this case, the
310 "c", "base", and "name" variables are omitted.
311
312 $template can be anything that Template::process understands how to
313 process, including the name of a template file or a reference to a test
314 string. See Template::process for a full list of supported formats.
315
316 To use the render method outside of your Catalyst app, just pass a
317 undef context. This can be useful for tests, for instance.
318
319 It is possible to forward to the render method of a TT view from inside
320 Catalyst to render page fragments like this:
321
322 my $fragment = $c->forward("View::Web", "render", $template_name, $c->stash->{fragment_data});
323
324 Backwards compatibility note
325
326 The render method used to just return the Template::Exception object,
327 rather than just throwing it. This is now deprecated and instead the
328 render method will throw an exception for new applications.
329
330 This behaviour can be activated (and is activated in the default
331 skeleton configuration) by using "render_die => 1". If you rely on the
332 legacy behaviour then a warning will be issued.
333
334 To silence this warning, set "render_die => 0", but it is recommended
335 you adjust your code so that it works with "render_die => 1".
336
337 In a future release, "render_die => 1" will become the default if
338 unspecified.
339
340 template_vars
341 Returns a list of keys/values to be used as the catalyst variables in
342 the template.
343
344 config
345 This method allows your view subclass to pass additional settings to
346 the TT configuration hash, or to set the options as below:
347
348 paths
349 The list of paths TT will look for templates in.
350
351 expose_methods
352 The list of methods in your View class which should be made available
353 to the templates.
354
355 For example:
356
357 expose_methods => [qw/uri_for_css/],
358
359 ...
360
361 sub uri_for_css {
362 my ($self, $c, $filename) = @_;
363
364 # additional complexity like checking file exists here
365
366 return $c->uri_for('/static/css/' . $filename);
367 }
368
369 Then in the template:
370
371 [% uri_for_css('home.css') %]
372
373 content_type
374 This lets you override the default content type for the response. If
375 you do not set this and if you do not set the content type in your
376 controllers, the default is "text/html; charset=utf-8".
377
378 Use this if you are creating alternative view responses, such as text
379 or JSON and want a global setting.
380
381 Any content type set in your controllers before calling this view are
382 respected and have priority.
383
384 "CATALYST_VAR"
385 Allows you to change the name of the Catalyst context object. If set,
386 it will also remove the base and name aliases, so you will have access
387 them through <context>.
388
389 For example, if CATALYST_VAR has been set to "Catalyst", a template
390 might contain:
391
392 The base is [% Catalyst.req.base %]
393 The name is [% Catalyst.config.name %]
394
395 "TIMER"
396 If you have configured Catalyst for debug output, and turned on the
397 TIMER setting, "Catalyst::View::TT" will enable profiling of template
398 processing (using Template::Timer). This will embed HTML comments in
399 the output from your templates, such as:
400
401 <!-- TIMER START: process mainmenu/mainmenu.ttml -->
402 <!-- TIMER START: include mainmenu/cssindex.tt -->
403 <!-- TIMER START: process mainmenu/cssindex.tt -->
404 <!-- TIMER END: process mainmenu/cssindex.tt (0.017279 seconds) -->
405 <!-- TIMER END: include mainmenu/cssindex.tt (0.017401 seconds) -->
406
407 ....
408
409 <!-- TIMER END: process mainmenu/footer.tt (0.003016 seconds) -->
410
411 "TEMPLATE_EXTENSION"
412 a suffix to add when looking for templates bases on the "match" method
413 in Catalyst::Request.
414
415 For example:
416
417 package MyApp::Controller::Test;
418 sub test : Local { .. }
419
420 Would by default look for a template in <root>/test/test. If you set
421 TEMPLATE_EXTENSION to '.tt', it will look for <root>/test/test.tt.
422
423 "PROVIDERS"
424 Allows you to specify the template providers that TT will use.
425
426 MyApp->config(
427 name => 'MyApp',
428 root => MyApp->path_to('root'),
429 'View::Web' => {
430 PROVIDERS => [
431 {
432 name => 'DBI',
433 args => {
434 DBI_DSN => 'dbi:DB2:books',
435 DBI_USER=> 'foo'
436 }
437 }, {
438 name => '_file_',
439 args => {}
440 }
441 ]
442 },
443 );
444
445 The 'name' key should correspond to the class name of the provider you
446 want to use. The _file_ name is a special case that represents the
447 default TT file-based provider. By default the name is will be
448 prefixed with 'Template::Provider::'. You can fully qualify the name
449 by using a unary plus:
450
451 name => '+MyApp::Provider::Foo'
452
453 You can also specify the 'copy_config' key as an arrayref, to copy
454 those keys from the general config, into the config for the provider:
455
456 DEFAULT_ENCODING => 'utf-8',
457 PROVIDERS => [
458 {
459 name => 'Encoding',
460 copy_config => [qw(DEFAULT_ENCODING INCLUDE_PATH)]
461 }
462 ]
463
464 This can prove useful when you want to use the
465 additional_template_paths hack in your own provider, or if you need to
466 use Template::Provider::Encoding
467
468 "CLASS"
469 Allows you to specify a custom class to use as the template class
470 instead of Template.
471
472 package MyApp::View::Web;
473 use Moose;
474 extends 'Catalyst::View::TT';
475
476 use Template::AutoFilter;
477
478 __PACKAGE__->config({
479 CLASS => 'Template::AutoFilter',
480 });
481
482 This is useful if you want to use your own subclasses of Template, so
483 you can, for example, prevent XSS by automatically filtering all output
484 through "| html".
485
486 HELPERS
487 The Catalyst::Helper::View::TT and Catalyst::Helper::View::TTSite
488 helper modules are provided to create your view module. There are
489 invoked by the myapp_create.pl script:
490
491 $ script/myapp_create.pl view Web TT
492
493 $ script/myapp_create.pl view Web TTSite
494
495 The Catalyst::Helper::View::TT module creates a basic TT view module.
496 The Catalyst::Helper::View::TTSite module goes a little further. It
497 also creates a default set of templates to get you started. It also
498 configures the view module to locate the templates automatically.
499
501 If you are using the CGI module inside your templates, you will
502 experience that the Catalyst server appears to hang while rendering the
503 web page. This is due to the debug mode of CGI (which is waiting for
504 input in the terminal window). Turning off the debug mode using the
505 "-no_debug" option solves the problem, eg.:
506
507 [% USE CGI('-no_debug') %]
508
510 Catalyst, Catalyst::Helper::View::TT, Catalyst::Helper::View::TTSite,
511 Template::Manual
512
514 Sebastian Riedel, "sri@cpan.org"
515
516 Marcus Ramberg, "mramberg@cpan.org"
517
518 Jesse Sheidlower, "jester@panix.com"
519
520 Andy Wardley, "abw@cpan.org"
521
522 Luke Saunders, "luke.saunders@gmail.com"
523
525 This program is free software. You can redistribute it and/or modify it
526 under the same terms as Perl itself.
527
528
529
530perl v5.36.0 2023-01-20 Catalyst::View::TT(3)