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