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