r20898@agaton (orig r755): wreis | 2008-07-24 00:32:56 +0100
[catagits/Reaction.git] / lib / Reaction / UI / RenderingContext / TT.pm
1 package Reaction::UI::RenderingContext::TT;
2
3 use Reaction::Class;
4 use aliased 'Reaction::UI::RenderingContext';
5 use aliased 'Template::View';
6
7 class TT is RenderingContext, which {
8
9   our $body;
10
11   implements 'dispatch' => as {
12     my ($self, $render_tree, $args) = @_;
13 #warn "-- dispatch start\n";
14     local $body = '';
15     my %args_copy = %$args;
16     foreach my $to_render (@$render_tree) {
17       my ($type, @to) = @$to_render;
18       if ($type eq '-layout') {
19         my ($lset, $fname, $next) = @to;
20         local $args_copy{call_next} =
21           (@$next
22             ? sub { $self->dispatch($next, $args); }
23             : '' # no point running internal dispatch if nothing -to- dispatch
24           );
25         $self->render($lset, $fname, \%args_copy);
26       } elsif ($type eq '-render') {
27         my ($widget, $fname, $over) = @to;
28         #warn "@to";
29         if (defined $over) {
30           my $count = 0;
31           $over->each(sub {
32             local $args_copy{_} = $_[0];
33             local $args_copy{count} = ++$count;
34             $body .= $widget->render($fname, $self, \%args_copy);
35           });
36         } else {
37           $body .= $widget->render($fname, $self, \%args_copy);
38         }
39       }
40     }
41 #warn "-- dispatch end, body: ${body}\n-- end body\nbacktrace: ".Carp::longmess()."\n-- end trace\n";
42     return $body;
43   };
44         
45   implements 'render' => as {
46     my ($self, $lset, $fname, $args) = @_;
47
48     confess "\$body not in scope" unless defined($body);
49   
50     # foreach non-_ prefixed key in the args
51     # build a subref for this key that passes self so the generator has a
52     # rendering context when [% key %] is evaluated by TT as $val->()
53     # (assuming it's a subref - if not just pass through)
54   
55     my $tt_args = {
56       map {
57         my $arg = $args->{$_};
58         ($_ => (ref $arg eq 'CODE' ? sub { $arg->($self, $args) } : $arg))
59       } grep { !/^_/ } keys %$args
60     };
61   
62     $body .= $lset->tt_view->include($fname, $tt_args);
63 #warn "rendered ${fname}, body length now ".length($body)."\n";
64   };
65
66 };
67
68 1;