Mercurial > pub > Impl
annotate Lib/IMPL/Web/TT/Document.pm @ 114:7084af955c57
minor changes, more strict code, no bugs fixed, no features added
author | wizard |
---|---|
date | Tue, 25 May 2010 01:26:42 +0400 |
parents | ddf0f037d460 |
children | 0475eb382085 |
rev | line source |
---|---|
77 | 1 package IMPL::Web::TT::Document; |
49 | 2 use strict; |
3 use warnings; | |
4 | |
75 | 5 use base qw(IMPL::DOM::Document IMPL::Object::Disposable); |
49 | 6 use Template::Context; |
7 use Template::Provider; | |
8 use IMPL::Class::Property; | |
9 use File::Spec; | |
77 | 10 use Scalar::Util qw(blessed); |
107 | 11 use IMPL::Web::TT::Collection; |
12 use IMPL::Web::TT::Control; | |
109
ddf0f037d460
IMPL::DOM::Node updated to support TT, (added childNodesRef and selectNodesRef for using from TT)
wizard
parents:
108
diff
changeset
|
13 use Carp; |
49 | 14 |
15 BEGIN { | |
77 | 16 private property _provider => prop_all; |
17 private property _context => prop_all; | |
18 public property template => prop_get | owner_set; | |
19 public property presenter => prop_all, { validate => \&_validatePresenter }; | |
108 | 20 private property _controlClassMap => prop_all; |
49 | 21 } |
22 | |
23 our %CTOR = ( | |
75 | 24 'IMPL::DOM::Document' => sub { nodeName => 'document' } |
49 | 25 ); |
26 | |
107 | 27 sub CTOR { |
28 my ($this) = @_; | |
29 | |
108 | 30 $this->_controlClassMap({}); |
31 $this->registerControlClass( Control => 'IMPL::Web::TT::Control' ); | |
32 $this->appendChild( $this->Create(body => 'IMPL::Web::TT::Collection') ); | |
33 $this->appendChild( $this->Create(head => 'IMPL::Web::TT::Collection') ); | |
34 } | |
35 | |
36 sub CreateControl { | |
37 my ($this,$name,$class,$args) = @_; | |
38 | |
39 $args = {} unless ref $args eq 'HASH'; | |
40 | |
41 if (my $info = $this->_controlClassMap->{$class}) { | |
42 my %nodeArgs = (%{$info->{args}},%$args); | |
43 $nodeArgs{controlClass} = $class; | |
44 | |
45 return $this->Create($name,$info->{type},\%nodeArgs); | |
46 } else { | |
47 die new IMPL::Exception('A control is\'t registered', $class, $name); | |
48 } | |
107 | 49 } |
50 | |
77 | 51 sub provider { |
49 | 52 my ($this,%args) = @_; |
53 | |
77 | 54 if (my $provider = $this->_provider) { |
49 | 55 return $provider; |
56 } else { | |
77 | 57 return $this->_provider(new Template::Provider( |
49 | 58 \%args |
59 )); | |
60 } | |
61 } | |
62 | |
77 | 63 sub context { |
49 | 64 my ($this) = @_; |
65 | |
77 | 66 if (my $ctx = $this->_context) { |
49 | 67 return $ctx; |
68 } else { | |
77 | 69 return $this->_context ( |
49 | 70 new Template::Context( |
71 VARIABLES => { | |
77 | 72 document => $this, |
73 this => $this, | |
74 render => sub { | |
75 $this->_process(@_); | |
108 | 76 } |
49 | 77 }, |
78 TRIM => 1, | |
79 RECURSION => 1, | |
77 | 80 LOAD_TEMPLATES => [$this->provider] |
49 | 81 ) |
82 ) | |
83 } | |
84 } | |
85 | |
108 | 86 sub registerControlClass { |
87 my ($this, $controlClass, $type, $args) = @_; | |
88 | |
89 $type ||= 'IMPL::Web::TT::Control'; | |
90 | |
91 die new IMPL::InvalidArgumentException("A controlClass must be a single word",$controlClass) unless $controlClass =~ /^\w+$/; | |
107 | 92 |
108 | 93 eval "require $type; 1;" or die new IMPL::Exception("Failed to load a module",$type,"$@") unless ref $type or $INC{$type}; |
94 | |
95 die new IMPL::InvalidArgumentException("A type must be subclass of IMPL::DOM::Node",$type) unless $type->isa('IMPL::DOM::Node'); | |
96 | |
97 $this->_controlClassMap->{$controlClass} = { | |
98 controlClass => $controlClass, | |
99 type => $type, | |
100 args => ref $args eq 'HASH' ? $args : {} | |
101 }; | |
107 | 102 } |
103 | |
109
ddf0f037d460
IMPL::DOM::Node updated to support TT, (added childNodesRef and selectNodesRef for using from TT)
wizard
parents:
108
diff
changeset
|
104 sub isControlClass { |
ddf0f037d460
IMPL::DOM::Node updated to support TT, (added childNodesRef and selectNodesRef for using from TT)
wizard
parents:
108
diff
changeset
|
105 my ($this,$name) = @_; |
ddf0f037d460
IMPL::DOM::Node updated to support TT, (added childNodesRef and selectNodesRef for using from TT)
wizard
parents:
108
diff
changeset
|
106 return $this->_controlClassMap->{$name} ? 1 : 0; |
ddf0f037d460
IMPL::DOM::Node updated to support TT, (added childNodesRef and selectNodesRef for using from TT)
wizard
parents:
108
diff
changeset
|
107 } |
ddf0f037d460
IMPL::DOM::Node updated to support TT, (added childNodesRef and selectNodesRef for using from TT)
wizard
parents:
108
diff
changeset
|
108 |
107 | 109 sub _getControls { |
110 my ($this) = @_; | |
111 | |
112 my ($node) = $this->selectNodes('controls'); | |
113 return $node; | |
114 } | |
115 | |
77 | 116 sub _validatePresenter { |
117 my ($this,$value) = @_; | |
118 | |
119 die new IMPL::InvalidArgumentException("A view object is required") unless blessed($value) and $value->isa('Template::View'); | |
120 } | |
121 | |
122 sub LoadFile { | |
49 | 123 my ($this,$filePath,$encoding) = @_; |
124 | |
125 die new IMPL::InvalidArgumentException("A filePath parameter is required") unless $filePath; | |
126 | |
127 $encoding ||= 'utf8'; | |
128 | |
77 | 129 $this->_context(undef); |
130 $this->_provider(undef); | |
49 | 131 |
132 my ($vol,$dir,$fileName) = File::Spec->splitpath($filePath); | |
133 | |
134 my $inc = File::Spec->catpath($vol,$dir,''); | |
135 | |
77 | 136 $this->provider( |
49 | 137 ENCODING => $encoding, |
138 INTERPOLATE => 1, | |
139 PRE_CHOMP => 1, | |
140 POST_CHOMP => 1, | |
141 INCLUDE_PATH => $inc | |
142 ); | |
143 | |
77 | 144 $this->template($this->context->template($fileName)); |
49 | 145 } |
146 | |
97 | 147 sub AddVar { |
148 my ($this,$name,$value) = @_; | |
149 | |
150 $this->context->stash->set($name,$value); | |
151 } | |
152 | |
77 | 153 sub title { |
154 $_[0]->template->title; | |
49 | 155 } |
156 | |
157 sub Render { | |
158 my ($this) = @_; | |
159 | |
77 | 160 return $this->template->process($this->context); |
161 } | |
162 | |
163 # Формирует представление для произвольных объектов | |
164 sub _process { | |
165 my ($this,@items) = @_; | |
166 | |
167 my @result; | |
168 | |
169 foreach my $item (@items) { | |
170 if (blessed($item) and $item->isa('IMPL::Web::TT::Control')) { | |
171 push @result, $item->Render(); | |
172 } elsif(blessed($item)) { | |
173 if ($this->presenter) { | |
174 push @result, $this->presenter->print($item); | |
175 } else { | |
176 push @result, $this->toString; | |
177 } | |
178 } else { | |
179 push @result, $item; | |
180 } | |
181 } | |
182 | |
107 | 183 return join '',@result; |
49 | 184 } |
185 | |
108 | 186 our $AUTOLOAD; |
187 sub AUTOLOAD { | |
188 my $this = shift; | |
189 my ($method) = ($AUTOLOAD =~ /(\w+)$/); | |
190 | |
191 if($method =~ /^create(\w+)/) { | |
192 my ($name,$args) = @_; | |
193 return $this->CreateControl($name,$1,$args); | |
194 } | |
195 | |
196 my @result = $this->selectNodes($method); | |
197 | |
198 return $result[0] if @result; | |
109
ddf0f037d460
IMPL::DOM::Node updated to support TT, (added childNodesRef and selectNodesRef for using from TT)
wizard
parents:
108
diff
changeset
|
199 carp "Looks like you have a mistake, document doesn't have a such property or child: $method"; |
108 | 200 return; |
201 } | |
202 | |
203 sub as_list { | |
204 $_[0]->childNodes; | |
205 } | |
206 | |
49 | 207 sub Dispose { |
208 my ($this) = @_; | |
209 | |
77 | 210 $this->template(undef); |
211 $this->_context(undef); | |
212 $this->_provider(undef); | |
49 | 213 |
108 | 214 $this->supercall::Dispose(); |
49 | 215 } |
216 | |
217 1; | |
218 __END__ | |
219 =pod | |
220 | |
77 | 221 =head1 NAME |
222 | |
223 C<IMPL::Web::TT::Document> - Документ, позволяющий строить представление по шаблону | |
224 | |
49 | 225 =head1 SYNOPSIS |
226 | |
75 | 227 =begin code |
228 | |
49 | 229 // create new document |
77 | 230 my $doc = new IMPL::Web::TT::Document; |
49 | 231 |
232 // load template | |
233 $doc->loadFile('Templates/index.tt'); | |
234 | |
235 // render file | |
236 print $doc->Render(); | |
237 | |
75 | 238 =end code |
239 | |
49 | 240 =head1 DESCRIPTION |
241 | |
77 | 242 C<use base qw(IMPL::DOM::Document)> |
243 | |
49 | 244 Документ, основанный на шаблоне Template::Toolkit. Позволяет загрузить шаблон, |
245 и сформировать окончательный документ. Является наследником C<IMPL::DOM::Node>, | |
246 т.о. может быть использован для реализации DOM модели. | |
247 | |
248 Внутри шаблона переменная C<document> ссылается на объект документа. По этой | |
249 причине образуется циклическая ссылка между объектами шаблона и документом, что | |
250 требует вызова метода C<Dispose> для освобождения документа. | |
251 | |
252 =head1 METHODS | |
253 | |
77 | 254 =over |
49 | 255 |
77 | 256 =item C<CTOR()> |
49 | 257 |
77 | 258 Создает новый экземпляр документа, свойство C<nodeName> устанавливается в 'C<document>' |
49 | 259 |
77 | 260 =item C<$doc->LoadFile($fileName,$encoding)> |
49 | 261 |
262 Загружает шаблон из файла C<$fileName>, используя кодировку C<$encoding>. Если | |
263 кодировка не указана, использует utf-8. | |
264 | |
265 =item C<$doc->Render()> | |
266 | |
267 Возвращает данные построенные на основе загруженного шаблона. | |
268 | |
269 =item C<$doc->Dispose()> | |
270 | |
271 Освобождает ресурсы и помечает объект как освобожденный. | |
272 | |
273 =back | |
274 | |
76 | 275 =head1 DOM |
276 | |
108 | 277 Документ представляет собой DOM документ, состоящий из узлов, которые представляют собой данные |
278 для отображения. Для форматированого вывода используется C<template>. | |
279 | |
280 В качестве элементов документа могут присутсвовать специальные объекты C<IMPL::Web::TT::Control>, | |
281 которые внутри содержат шаблон для форматирования собственного содержимого. | |
282 | |
283 | |
284 | |
285 Документ предоставляет ряд фнукций для работы с элементами управления. | |
286 | |
287 =head1 TEMPLATE | |
288 | |
77 | 289 =begin code html |
76 | 290 |
108 | 291 [% CALL document.registerClass( 'Table', 'My::TableClass', template => 'tables/pretty.tt' ) %] |
292 [% CALL document.registerClass( 'Form' )%] | |
293 | |
294 [% table = document.сreateTable('env') %] | |
76 | 295 |
296 [% FOEACH item in document.result %] | |
297 [% table.rows.Add( item.get('name','value') ) %] | |
298 [% END %] | |
299 | |
108 | 300 [% form = document.createForm('login') %] |
77 | 301 [% form.template = 'LOGIN_FORM'%] |
302 | |
303 [% FOREACH item IN document.childNodes %] | |
304 [%render(item)%] | |
76 | 305 [% END %] |
306 | |
77 | 307 [% BLOCK LOGIN_FORM %] |
308 <form method="POST" action='/login.pl'> | |
309 user: [% render(this.item('name')) %] password: [% render(this.item('password')) %] <input type="submit"/> | |
310 </form> | |
311 [% END %] | |
76 | 312 |
77 | 313 =end code html |
76 | 314 |
49 | 315 =cut |