Controller/Render/Template.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Controller/Methods.pm ↑ Summary Controller/Const.pm »
1 package Apache2::Controller::Render::Template;
2  
3 =head1 NAME
4  
5 Apache2::Controller::Render::Template - A2C render() with Template Toolkit
6  
7 =head1 VERSION
8  
9 Version 1.001.001
10  
11 =cut
12  
13 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 our $VERSION = version->new('1.001.001');
15  
16 =head1 SYNOPSIS
17  
18 # apache2 config file
19  
20 PerlLoadModule Apache2::Controller::Directives
21 PerlLoadModule Apache2::Controller::DBI::Connector
22  
23 # location of templates - must be defined
24 A2C_Render_Template_Path /var/myapp/templates /var/myapp/template_components
25  
26 <Location /foo>
27 SetHandler modperl
28 PerlInitHandler MyApp::Dispatch::Foo
29  
30 # set directives A2C_DBI_DSN, etc.
31 PerlHeaderParserHandler Apache2::Controller::DBI::Connector
32 </Location>
33  
34 See L<Apache2::Controller::Dispatch> for A2C Dispatch implementations.
35  
36 See L<Apache2::Controller::Directives> and L<Apache2::Controller::DBI::Connector>.
37  
38 package MyApp::C::Bar; # let's assume this controller was dispatched
39  
40 use strict;
41 use warnings;
42  
43 use base qw(
44 Apache2::Controller
45 Apache2::Controller::Render::Template
46 );
47  
48 use Apache2::Const -compile => qw( HTTP_OK );
49  
50 sub allowed_methods {qw( default )}
51  
52 sub default {
53 my ($self, @first, @last) = @_;
54 my @path_args = $self->my_detaint_path_args('name'); # from $self->{path_args}
55  
56 $self->{stash}{creditcards} = $self->pnotes->{a2c}{dbh}->fetchall_arrayref(
57 q{ SELECT ccnum, exp, addr1, zip, cac
58 FROM customer_credit_cards
59 WHERE lname = ? AND fname = ?
60 }, undef, @path_args
61 );
62  
63 # request was like http://myserver.xyz/foo/Larry/Wall
64  
65 $self->render(); # renders /var/myapp/templates/foo/default.html
66 return Apache2::Const::HTTP_OK;
67  
68 }
69  
70 __END__
71 [%# /var/myapp/templates/foo/default.html %]
72 <p>Here is the credit card info you requested for
73 everyone named [% path_args.reverse.join(' ') %]:</p>
74 <ul>
75 [% FOREACH card = creditcards %]
76 [% FOREACH field = ['ccnum','exp','addr1','zip','cac'] %]
77 <li><strong>[% field %]:</strong> [% card.$field %]</li>
78 [% END %]
79 [% END %]
80 </ul>
81 [%# end template toolkit file %]
82  
83  
84 =head1 DESCRIPTION
85  
86 This module provides a nice rendering mechanism for Apache2::Controller.
87  
88 =head1 TEMPLATE OPTIONS
89  
90 You can specify options for L<Template> in one of two ways:
91  
92 =head2 DIRECTIVES
93  
94 By using
95 L<Apache2::Controller::Directives/A2C_Render_Template_Opts>:
96  
97 <Location '/foo'>
98 A2C_Render_Template_Opts INTERPOLATE 1
99 A2C_Render_Template_Opts PRE_PROCESS header
100 A2C_Render_Template_Opts POST_CHOMP 1
101 </Location>
102  
103 =head2 METHOD template_options()
104  
105 Or by implementing C<<template_options>> in your controller:
106  
107 package MyApp::Controller;
108 use base qw( Apache2::Controller Apache2::Controller::Render::Template );
109 sub allowed_methods {qw( default )}
110  
111 sub template_options {
112 my ($self) = @_;
113 return {
114 INTERPOLATE => 1,
115 PRE_PROCESS => 'header',
116 POST_CHOMP =. 1,
117 };
118 }
119  
120 sub default {
121 # ...
122 }
123  
124 =head1 STASH FUNCTIONS
125  
126 We don't assign any stash functions by default.
127 If you want to assign consistent stash functions in your controller,
128 overload C<< render() >>, assign them, and then call C<< SUPER::render() >>.
129  
130 package MyApp::ControllerBase;
131 use base qw( Apache2::Controller Apache2::Controller::Render::Template );
132 use HTML::Entities;
133  
134 sub render {
135 my ($self) = @_;
136 $self->{stash}{encode_entities} = \&encode_entities;
137 $self->SUPER::render();
138 }
139  
140 package MyApp::Controller::Somewhere;
141 use base qw( MyApp::ControllerBase );
142 # ...
143 sub someuri {
144 my ($self, @path_args) = @_;
145 $self->render();
146 return Apache2::Const::HTTP_OK;
147 }
148  
149  
150 =cut
151  
152 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
153 2 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
154 2 ▶use English '-no_match_vars';
Subroutine BEGIN: called CC=1 SCAR=0.0
155  
156 0 ▶use Apache2::Const -compile => qw( SERVER_ERROR );
Subroutine BEGIN: called CC=1 SCAR=2.6
157 use Apache2::Controller::X;
158  
159 use File::Spec;
160 use Template;
161 use YAML::Syck;
162 use HTTP::Status qw( status_message );
163 use Log::Log4perl qw( :easy );
164  
165 sub _assign_tt_stash_data {
166 my ($self) = @_;
167 my $stash = $self->{stash} ||= { };
168 my $stash_a2c = $stash->{a2c} ||= { };
169 my @keys = qw( path_args method controller );
170 @{$stash_a2c}{@keys} = @{$self}{@keys};
171 return;
172 }
173  
174 =head1 METHODS
175  
176 =head2 render
177  
178 render() accumulates template output into a variable
179 before printing, so it may use a lot of memory
180 if you expect a large data set.
181  
182 It does this so it can intercept Template errors
183 and kick up an exception to be printed using your
184 error templates. See error().
185  
186 =cut
187  
188 sub render {
189 my ($self) = @_;
190  
191 DEBUG("beginning render()");
192  
193 my $tt = $self->get_tt_obj();
194 my $template = $self->detect_template();
195 DEBUG("processing template = '$template'");
196  
197 # DEBUG(sub { Dump($self->{stash}) });
198  
199 $self->_assign_tt_stash_data();
200  
201 # assimilate output to a scalar
202 my $output;
203 my $ok = $tt->process($template, $self->{stash}, \$output);
204  
205 if (!$ok) {
206 my $tt_err = $tt->error();
207  
208 my ($type, $info) = $tt_err->type_info; # see Template::Exception
209 my $status_code
210 = $type eq 'file' && $info =~ m{ not \s+ found }mxs
211 ? Apache2::Const::NOT_FOUND
212 : Apache2::Const::SERVER_ERROR
213 ;
214  
215 a2cx message => "$type error - $info",
216 status => $status_code,
217 status_line => "$status_code $type error - $info",
218 ;
219 }
220  
221 $self->print($output);
222  
223 return;
224 }
225  
226 =head2 render_fast
227  
228 So if you are planning to get a large
229 data set, you probably want to use $self->render_fast()
230 and put the database query handle somewhere in $self->{stash}
231 and call fetchrow() in a Template block.
232  
233 With render_fast(), Template->process() outputs directly to
234 Apache2::Request->print(). So if a Template error is encountered,
235 some output may have already been sent to the browser, resulting
236 in a completely screwed up screen when the exception is kicked
237 back up to the server.
238  
239 Tip: if you plan to use render_fast(), write a test suite that
240 tests the output of your page.
241  
242 Of course you could bypass rendering altogether and just use
243 $self->print(). (Remember that $self is
244 normally subclassed in L<Apache2::Request> which magically
245 delegates to C<< $self->{r} >>.)
246 Or maybe you should implement an ajax style control in the template
247 and put a limit frame on the query above, or use a paging lib, etc. ...
248  
249 =cut
250  
251 sub render_fast {
252 my ($self) = @_;
253  
254 $self->pnotes->{a2c}{use_standard_errors} = 1;
255  
256 my $template = $self->detect_template();
257 DEBUG("processing template = '$template'");
258  
259 # DEBUG(sub { Dump($self->{stash}) });
260  
261 $self->_assign_tt_stash_data();
262  
263 my $tt = $self->get_tt_obj();
264 # pass Apache2::Request object to print directly.
265 $tt->process($template, $self->{stash}, $self->{r}) || a2cx $tt->error();
266  
267 return;
268 }
269  
270 =head2 error
271  
272 If your template directory contains a subdirectory named 'error',
273 then when the controller throws an exception, the exception object will
274 be passed to a selected error template as 'X' in the stash. It also
275 sets status (number) and status_line
276 (from HTTP::Status::status_message() or from the values
277 set in the L<Apache2::Controller::X> exception).
278  
279 If you have a template $template_dir/error/$status.html,
280 where $status is the numeric http status code,
281 then it will use that template.
282  
283 For example:
284  
285 203 HTTP_NON_AUTHORITATIVE => error/203.html
286 400 HTTP_BAD_REQUEST => error/400.html
287 404 NOT_FOUND => error/404.html
288 500 HTTP_INTERNAL_SERVER_ERROR => error/500.html
289  
290 For example, C<$template_dir/error/400.html> or
291 C<$template_dir/error/403.html>.
292  
293 Otherwise it will look for $template_dir/error/default.html and
294 try to use that, otherwise it will give up.
295  
296 error() remembers across requests whether you do or don't have
297 error templates for certain messages in the appropriate template directory,
298 so it will be faster the second time around if you use error/default.html.
299  
300 For a reference list of status and messages, see Apache2::Controller.
301  
302 Since render_fast() is incompatible if a template rendering error
303 occurs, render_fast() turns off the use of error() and relies on
304 standard Apache2 error messages (or the custom message set in
305 the exception object) and relies on the browser to display them.
306  
307 =cut
308  
309 my %error_templates = ( );
310  
311 sub error {
312 my ($self, $X) = @_;
313  
314 my ($status, $status_line);
315  
316 DEBUG("original error: '$X'");
317  
318 if (ref($X) && $X->isa('Apache2::Controller::X')) {
319 $status = $X->status;
320 $status_line = $X->status_line;
321 DEBUG("got status from \$X: ".($status || '[none]'));
322 }
323 $status ||= Apache2::Const::SERVER_ERROR;
324 $status_line ||= $status.' '.status_message($status);
325  
326 my $status_file = $status;
327 DEBUG("status msg for $status_file: '$status_line'");
328  
329 $self->{stash}{X} = $X;
330 $self->{stash}{status_line} = $status_line;
331 $self->{stash}{status} = $status;
332  
333 my $template_dir = $self->get_directive('A2C_Render_Template_Path')
334 || a2cx 'A2C_Render_Template_Path not defined.';
335  
336 DEBUG sub { "A2C_Render_Template_Path:\n".Dump($template_dir) };
337  
338 if (exists $error_templates{$template_dir}{$status_file}) {
339  
340 my $template = $error_templates{$template_dir}{$status_file};
341
342 # if exists but undefined, it means it failed totally.
343 # forget about using an error template and just rethrow the error
344 if (!defined $template) {
345 if (ref($X) && $X->isa('Apache2::Controller::X')) {
346 $X->rethrow();
347 }
348 else {
349 a2cx "Cannot process any template for unknown-type error: $X";
350 }
351 }
352  
353 $self->{template} = $template;
354 $self->render();
355 }
356 else {
357 # does the error directory even exist?
358  
359 # first try the appropriately named file:
360 my %try_errors = ( );
361 $self->{template} = "errors/$status_file.html";
362 eval { $self->render() };
363  
364 # if got an error using that file name, try the default error file:
365 if ($EVAL_ERROR) {
366 $try_errors{$self->{template}} = "$EVAL_ERROR";
367 $self->{template} = "errors/default.html";
368 eval { $self->render() };
369  
370 # and if error template doesn't work, throw back original error
371 if ($EVAL_ERROR) {
372 DEBUG "Error rendering error file: $EVAL_ERROR";
373 $try_errors{$self->{template}} = "$EVAL_ERROR";
374 $error_templates{$template_dir}{$status_file} = undef;
375 if (ref $X && $X->isa('Apache2::Controller::X')) {
376 $X->rethrow();
377 }
378 else {
379 my $dump = { tries => \%try_errors, reftype => ref $X };
380 a2cx message => "$X",
381 status => $status,
382 status_line => $status_line,
383 'dump' => $dump;
384 }
385 }
386 }
387  
388 # after finding the right template for code, remember it for next time
389 $error_templates{$template_dir}{$status_file} = $self->{template};
390 }
391 return;
392 }
393  
394 =head2 detect_template
395  
396 This is called internally by the render methods, but you can use
397 it to figure out the default template from where you are.
398  
399 To override the auto-select template, just set $self->{template}
400 before you call C<<render()>>.
401  
402 It looks for templates in a computed directory. The directory where it
403 looks will always be the directory set with the A2C_Render_Template_Path
404 directive in the config file, appended with the current request location,
405 i.e. the directory of the Location directive in the config file,
406 appended with relative_uri, appended with method name and '.html'.
407  
408 A2C_Render_Template_Path + location + relative_uri + method.html
409  
410 For example, the sequence in SYNOPSIS above renders the file
411 C</var/myapp/templates/foo/default.html> .
412  
413 Suppose the dispatch class above dispatches sub-path uris starting
414 with 'bar/biz' to another controller. That controller would look for
415 templates in the directory /var/myapp/templates/foo/bar/biz/methodname.html.
416  
417 Example:
418  
419 Request: http://myserver.xyz/foo/bar/biz/baz/boz/noz
420  
421 location = /foo
422  
423 relative_uri = bar/biz
424  
425 controller MyApp::C::Foo::Bar::Biz # mapped in your A2C Dispatch
426  
427 found method = baz
428  
429 path_args = [ boz, noz ]
430  
431 template = /var/myapp/templates + /foo + /bar/biz + /baz.html
432  
433 /var/myapp/templates/foo/bar/biz/baz.html
434  
435 $self->{relative_uri} is the uri relative to the location,
436 so in other words:
437  
438 location + relative_uri == full uri - path args
439  
440 See Apache2::Controller::Dispatch::Simple.
441  
442 =cut
443  
444 sub detect_template {
445 my ($self) = @_;
446  
447 if (exists $self->{template}) {
448 DEBUG("have a template already, returning $self->{template}");
449 return $self->{template};
450 }
451  
452 (my $rel_uri = ($self->pnotes->{a2c}{relative_uri} || '') ) =~ s{ \A / }{}mxs;
453 my $loc = $self->location();
454 my $file = "$self->{method}.html";
455  
456 DEBUG(sub{ "before detect_template() changes:\n".Dump({
457 loc => $loc,
458 rel_uri => $rel_uri,
459 file => $file,
460 })});
461  
462 # trim leading and trailing /'s
463 $loc = '' if $loc eq '/';
464 if ($loc) {
465 $loc = substr($loc, 1) if length $loc > 1 && substr($loc, 0, 1) eq '/';
466 substr($loc, -1, 1, '') if substr($loc, -1) eq '/';
467 }
468  
469 my @file_spec_parts = grep {($_)} $loc, $rel_uri, $file;
470 my $template = File::Spec->catfile(@file_spec_parts);
471  
472 DEBUG(sub{ "after detect_template() changes:\n".Dump({
473 loc => $loc,
474 rel_uri => $rel_uri,
475 file => $file,
476 template => $template,
477 })});
478  
479 a2cx "bad template path $_" if $template =~ m{ \.\. / }mxs;
480  
481 $self->{template} = $template;
482 return $template;
483 }
484  
485 =head2 get_tt_obj
486  
487 Get the L<Template> object set up with the appropriate include directory
488 set from the directive C<<A2C_Render_Template_Path>>.
489  
490 Directive C<A2C_Render_Template_Opts> sets default C<new()>
491 options for L<Template>.
492  
493 =cut
494  
495 my %implements_template_opts;
496 my %tts = ();
497 sub get_tt_obj {
498 my ($self) = @_;
499  
500 my $include_path = $self->get_directive('A2C_Render_Template_Path')
501 || a2cx "A2C_Render_Template_Path not defined";
502  
503 my $class = $self->{class};
504 $implements_template_opts{$class} = $self->can('template_opts')
505 if !exists $implements_template_opts{$class};
506  
507 my %opts
508 = $implements_template_opts{$class}
509 ? %{ $self->template_opts() }
510 : %{ $self->get_directive('A2C_Render_Template_Opts') || { } };
511  
512 $opts{INCLUDE_PATH}
513 = !$opts{INCLUDE_PATH} ? $include_path
514 : ref $opts{INCLUDE_PATH} ? [@{$opts{INCLUDE_PATH}}, @{$include_path}]
515 : [$opts{INCLUDE_PATH}, @{$include_path}];
516  
517 my $opts_key = Dump(\%opts);
518 DEBUG("using opts for new TT on $include_path:\n$opts_key");
519  
520 return $tts{$opts_key} if exists $tts{$opts_key};
521  
522 my $tt;
523
524 eval { $tt = Template->new(\%opts) || die $Template::ERROR."\n" };
525 a2cx "No TT for $include_path: $EVAL_ERROR" if $EVAL_ERROR;
526  
527 $tts{$opts_key} = $tt;
528  
529 return $tt;
530 }
531  
532 =head1 SEE ALSO
533  
534 L<Apache2::Controller>
535  
536 L<Apache2::Controller::Render::Template>
537  
538 L<Apache2::Controller::X>
539  
540 =head1 AUTHOR
541  
542 Mark Hedges, C<< <hedges at--! formdata.biz> >>
543  
544 =head1 COPYRIGHT & LICENSE
545  
546 Copyright 2008-2010 Mark Hedges, all rights reserved.
547  
548 This program is free software; you can redistribute it and/or modify it
549 under the same terms as Perl itself.
550  
551 This software is provided as-is, with no warranty
552 and no guarantee of fitness
553 for any particular purpose.
554  
555 =cut
556  
557  
558 1;
« Controller/Methods.pm ↑ Summary Controller/Const.pm »