Mercurial > pub > Impl
annotate Lib/IMPL/Web/View/TTLoader.pm @ 336:86336d451b82
sync
author | cin |
---|---|
date | Fri, 14 Jun 2013 03:32:55 +0400 |
parents | d3b5a67ad2e8 |
children | 9bdccdf1f50b |
rev | line source |
---|---|
181 | 1 package IMPL::Web::View::TTLoader; |
2 use strict; | |
3 | |
4 use Template::Constants qw(:status); | |
5 | |
336 | 6 use File::Spec(); |
265 | 7 use IMPL::Const qw(:prop); |
8 use IMPL::declare { | |
9 require => { | |
10 Provider => 'Template::Provider', | |
11 Context => 'Template::Context', | |
309 | 12 TTRegistry => 'IMPL::Web::View::TTRegistry', |
308 | 13 TTFactory => 'IMPL::Web::View::TTFactory', |
309 | 14 TTDocument => '-IMPL::Web::View::TTDocument', |
265 | 15 Exception => 'IMPL::Exception', |
16 ArgumentException => '-IMPL::InvalidArgumentException', | |
17 KeyNotFoundException => '-IMPL::KeyNotFoundException' | |
18 }, | |
19 base => [ | |
20 'IMPL::Object' => undef, | |
21 'IMPL::Object::Serializable' => undef | |
22 ], | |
23 props => [ | |
24 options => PROP_RO, | |
25 provider => PROP_RO, | |
26 context => PROP_RO, | |
27 ext => PROP_RO, | |
28 layoutBase => PROP_RO, | |
29 isInitialized => PROP_RO, | |
30 initializer => PROP_RO, | |
31 _globals => PROP_RW | |
32 ] | |
33 }; | |
181 | 34 |
196 | 35 sub save { |
36 my ($this,$context) = @_; | |
37 | |
38 $context->AddVar($_, $this->$_()) for qw(options provider context ext layoutBase); | |
39 } | |
40 | |
41 sub restore { | |
42 my ($class,$data,$surrogate) = @_; | |
43 | |
44 my %params = @$data; | |
45 | |
46 my $refOpts = delete $params{options}; | |
47 | |
48 if ($surrogate){ | |
49 $surrogate->callCTOR($refOpts,%params); | |
50 } else { | |
51 $surrogate = $class->new($refOpts,%params); | |
52 } | |
206 | 53 return $surrogate; |
196 | 54 } |
55 | |
181 | 56 sub CTOR { |
194 | 57 my ($this,$refOpts,%args) = @_; |
58 | |
59 $refOpts ||= {}; | |
60 | |
61 $this->ext($args{ext}) if $args{ext}; | |
62 $this->initializer($args{initializer}) if $args{initializer}; | |
63 $this->_globals(ref $args{globals} eq 'HASH' ? $args{globals} : {}); | |
64 | |
65 $this->options($refOpts); | |
195
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
66 $this->layoutBase($args{layoutBase}) if $args{layoutBase}; |
194 | 67 |
68 # to aviod cyclic references we need to do a copy of $refOpts | |
265 | 69 $refOpts->{LOAD_TEMPLATES} = $this->provider(Provider->new( { %$refOpts } )); |
194 | 70 |
265 | 71 $this->context(Context->new($refOpts)); |
181 | 72 } |
73 | |
74 sub document { | |
194 | 75 my ($this,$name,$vars) = @_; |
76 | |
309 | 77 $vars ||= {}; |
308 | 78 |
194 | 79 my $tt = $this->template($name); |
80 | |
81 $this->_init(); | |
82 | |
83 my $opts = { %{ $this->options } }; | |
84 | |
287 | 85 $this->context->localise(); |
289 | 86 my $ctx = _clone_context($this->context); |
287 | 87 $this->context->delocalise(); |
194 | 88 |
311 | 89 $ctx->stash->update($vars); |
90 | |
309 | 91 my $registry = TTRegistry->new($this, $ctx); |
92 | |
93 my $factory = TTFactory->new($tt->class || TTDocument, $tt, $ctx, $name, $registry); | |
308 | 94 |
309 | 95 $vars->{registry} = $registry; |
310
0a9d51cf6dfd
*TTView: refactoring, document supports custom classes, layouts are become controls
sergey
parents:
309
diff
changeset
|
96 $vars->{layoutBase} = $this->layoutBase; |
309 | 97 |
311 | 98 return $factory->new( $vars ); |
181 | 99 } |
100 | |
308 | 101 |
181 | 102 sub template { |
194 | 103 my ($this,$name) = @_; |
104 | |
105 $name =~ s/^\s+|\s+$//g; | |
106 | |
265 | 107 die ArgumentException->new("A valid template name is required") unless length $name; |
194 | 108 |
109 $name = $this->_appendExt($name); | |
110 | |
111 my ($tt,$error) = $this->provider->fetch($name); | |
112 | |
113 if (defined $error and $error == STATUS_DECLINED) { | |
285
546957c50a36
*IMPL::Web::Handler::TTView Reworked template selection mechanism
cin
parents:
265
diff
changeset
|
114 die KeyNotFoundException->new($name); |
194 | 115 } elsif (defined $error and $error == STATUS_ERROR) { |
265 | 116 die Exception->new("Failed to load a template", $name, $tt); |
194 | 117 } |
118 | |
119 return $tt; | |
181 | 120 } |
121 | |
336 | 122 sub ResolveFileName { |
123 my ($this,$fname) = @_; | |
124 | |
125 $fname = $this->_appendExt($fname); | |
126 | |
127 my @files = grep -f , map File::Spec->catfile($_,$fname), @{$this->provider->paths()}; | |
128 return shift @files; | |
129 } | |
130 | |
181 | 131 sub _appendExt { |
194 | 132 my ($this,$name) = @_; |
133 | |
134 return $name unless $this->ext; | |
135 | |
136 if (length $this->ext and substr( $name, -length($this->ext) ) eq $this->ext) { | |
137 return $name; | |
138 } else { | |
139 return $name . $this->ext; | |
140 } | |
181 | 141 } |
142 | |
143 sub _init { | |
194 | 144 my ($this) = @_; |
145 | |
146 if (!$this->isInitialized) { | |
147 my $initializer = $this->initializer || sub {}; | |
148 | |
149 eval { | |
150 $this->context->process($initializer,$this->_globals); | |
151 }; | |
152 if (my $e = $@) { | |
265 | 153 die Exception->new("Failed to process an initializer", $this->initializer, $e); |
194 | 154 } |
155 | |
156 $this->isInitialized(1); | |
157 } | |
181 | 158 } |
159 | |
289 | 160 sub _clone_context { |
161 my $args = { %{shift || {}} }; | |
162 delete $args->{CONFIG}; | |
163 | |
164 return Template::Context->new($args); | |
165 } | |
166 | |
181 | 167 1; |
168 | |
169 __END__ | |
170 | |
171 =pod | |
172 | |
173 =head1 NAME | |
174 | |
175 C<IMPL::Web::View::TTLoader> - предоставляет глобальный контекст для загрузки шаблонов | |
176 | |
177 =head1 SYNOPSIS | |
178 | |
179 =begin code | |
180 | |
181 use IMPL::Web::View::TTLoader(); | |
182 | |
183 my $loader = new IMPL::Web::View::TTLoader( | |
194 | 184 { |
185 INCLUDE_PATH => [ | |
186 '/my/app/tt', | |
187 '/my/app/tt/lib' | |
188 ] | |
189 }, | |
190 ext => '.tt', | |
191 initializer => 'shared/global' | |
192 | |
181 | 193 ); |
194 | |
195 my $doc = $loader->document('index'); | |
196 | |
197 my $html = $doc->Render(); | |
198 | |
199 =end code | |
200 | |
201 =head1 DESCRIPTION | |
202 | |
265 | 203 Провайдер для загрузки шаблонов и документов. Имеет собственное пространство |
204 имен, контекст выполнения шаблонов. Контект загрузчика инициализируется | |
205 шаблоном, в котором определяются глобальные переменные, которые будут доступны | |
206 в документах, однако их изменения будут локализованы. | |
207 | |
208 Инициализация контекста провайдера происходит при первой загрузке любого | |
209 документа. | |
210 | |
182 | 211 =head1 MEMBERS |
212 | |
265 | 213 =head2 C<CTOR($options,%args)> |
214 | |
215 =over | |
216 | |
217 =item * C<$options> | |
218 | |
219 Параметры контекста загрузчика, контексты документов и элементов управления | |
220 также унаследуют эти свойства. Напрямую передаются в конструктор | |
221 C<Template::Context>. | |
222 | |
223 =item * C<%args> | |
224 | |
225 Именованные параметы загрузчика. | |
226 | |
227 =over | |
228 | |
229 =item * C<ext> | |
230 | |
231 Расширение, которое будет добавляться к именам шаблонов и документов (если оно | |
232 не будет указано явно). | |
233 | |
234 =item * C<initializer> | |
235 | |
236 Имя шаблона, который будет использован для инициализации контекста. | |
237 | |
238 =item * C<globals> | |
239 | |
240 Глобальные переменнын, которые будут переданы в контекст. | |
241 | |
242 =item * C<layoutBase> | |
243 | |
244 Путь к шаблонам для оформления документов. Каждый документ может задавать свой | |
245 C<layout> указанный в его C<META> блоке или конструкторе. | |
246 См. C<IMPL::View::TTDocument>. | |
247 | |
248 =back | |
249 | |
250 =back | |
251 | |
182 | 252 =head2 C<document($docName)> |
253 | |
265 | 254 Загружает документ с именем C<$docName>. При необходимости к нему будет |
255 добавлено расширение, указанное в свойстве C<ext>. Это единственно полезный | |
256 метод провайдера. | |
257 | |
181 | 258 =cut |
259 |