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