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