]> git.decadent.org.uk Git - maypole.git/blob - lib/Maypole/View/Base.pm
Finished view documentation, refactor TT->base, and add Mason view class.
[maypole.git] / lib / Maypole / View / Base.pm
1 package Maypole::View::Base;
2 use File::Spec;
3 use UNIVERSAL::moniker;
4 use strict;
5
6 sub new { bless {}, shift } # By default, do nothing.
7
8 sub paths {
9     my ($self, $r) = @_;
10     my $root = $r->{config}{template_root} || $r->get_template_root;
11     return (
12         $root,
13         ($r->model_class && 
14             File::Spec->catdir($root, $r->model_class->moniker)),
15         File::Spec->catdir($root, "custom"),
16         File::Spec->catdir($root, "factory")
17     );
18 }
19
20 sub vars {
21     my ($self, $r) = @_;
22     my $class = $r->model_class;
23     my %args = (
24         request => $r,
25         objects => $r->objects,
26         base    => $r->config->{uri_base},
27         config  => $r->config
28         # ...
29     ) ;
30     if ($class) { 
31         $args{classmetadata} = {
32             name => $class,
33             table => $class->table,
34             columns => [ $class->display_columns ],
35             colnames => { $class->column_names },
36             related_accessors => [ $class->related($r) ],
37             moniker => $class->moniker,
38             plural  => $class->plural_moniker,
39             cgi => { $class->to_cgi },
40             description => $class->description
41         };
42
43         # User-friendliness facility for custom template writers.
44         if (@{$r->objects || []} > 1) { 
45             $args{$r->model_class->plural_moniker} = $r->objects;
46         } else {
47             ($args{$r->model_class->moniker}) = @{$r->objects ||[]};
48         }
49     }
50
51     # Overrides
52     %args = (%args, %{$r->{template_args}||{}});
53     %args;
54 }
55
56 sub do_it {
57     my ($self, $r) = @_;
58     my $template = Template->new({ INCLUDE_PATH => [ $self->paths($r) ]});
59     my $output;
60     if ($template->process($r->template, { $self->args($r) }, \$output)) {
61         $r->{output} = $output;
62         return 1;
63     } else { 
64          $r->{error} = $template->error;
65     }
66
67 }
68
69 sub process {
70     my ($self, $r) = @_;
71     $self->template($r) || return $self->error($r);
72     $r->{content_type} ||= "text/html";
73     return 200;
74 }
75
76 sub error {
77     my ($self, $r) = @_;
78     warn $r->{error};
79     if ($r->{error} =~ /not found$/) { return -1 }
80     $r->{content_type} = "text/plain";
81     $r->{output} = $r->{error};
82     $r->send_output;
83 }
84
85 sub template { die shift()." didn't define a decent template method!" }
86
87 1;