]> git.decadent.org.uk Git - maypole.git/blob - lib/Maypole/View/TT.pm
Miscellaneous fixes.
[maypole.git] / lib / Maypole / View / TT.pm
1 package Maypole::View::TT;
2 use Apache::Constants;
3 use Lingua::EN::Inflect;
4 use Template;
5 use File::Spec;
6 use UNIVERSAL::moniker;
7 use strict;
8
9
10 sub new { bless {}, shift } # Not worth having
11
12 sub _tt {
13     my ($self, $r) = @_;
14     my $root = $r->{ar}->document_root . "/". $r->{ar}->location;
15     Template->new({ INCLUDE_PATH => [
16         $root,
17         ($r->model_class && File::Spec->catdir($root, $r->model_class->moniker)),
18         File::Spec->catdir($root, "custom"),
19         File::Spec->catdir($root, "factory")
20     ]});
21 }
22
23 sub _args {
24     my ($self, $r) = @_;
25     my $class = $r->model_class;
26     my %args = (
27         request => $r,
28         objects => $r->objects,
29         base    => $r->config->{uri_base},
30         config  => $r->config
31         # ...
32     ) ;
33     if ($class) { 
34         $args{classmetadata} = {
35             name => $class,
36             columns => [ $class->display_columns ],
37             colnames => { $class->column_names },
38             related_accessors => [ $class->related($r) ],
39             moniker => $class->moniker,
40             plural  => $class->plural_moniker,
41             cgi => { $class->to_cgi },
42             description => $class->description
43         };
44
45         # User-friendliness facility for custom template writers.
46         if (@{$r->objects || []} > 1) { 
47             $args{$r->model_class->plural_moniker} = $r->objects;
48         } else {
49             ($args{$r->model_class->moniker}) = @{$r->objects ||[]};
50         }
51     }
52
53     # Overrides
54     %args = (%args, %{$r->{template_args}||{}});
55     %args;
56 }
57
58 sub process {
59     my ($self, $r) = @_;
60     my $template = $self->_tt($r);
61     my $output;
62     $template->process($r->template, { $self->_args($r) }, \$output)
63     || return $self->error($r, $template->error);
64
65     $r->{ar}->content_type("text/html");
66     $r->{ar}->headers_out->set("Content-Length" => length $output);
67     $r->{ar}->send_http_header;
68     $r->{ar}->print($output);
69     return 200;
70 }
71
72 sub error {
73     my ($self, $r, $error) = @_;
74     warn $error;
75     if ($error =~ /not found$/) { return DECLINED }
76     $r->{ar}->send_http_header("text/plain");
77     $r->{ar}->print($error);
78     exit;
79 }
80
81 1;