Mercurial > pub > Impl
annotate Lib/IMPL/Web/View/TTLoader.pm @ 309:5e4e7c8fbca1
sync
author | cin |
---|---|
date | Fri, 19 Apr 2013 00:27:51 +0400 |
parents | 47a09a8dc23a |
children | 0a9d51cf6dfd |
rev | line source |
---|---|
181 | 1 package IMPL::Web::View::TTLoader; |
2 use strict; | |
3 | |
4 use Template::Constants qw(:status); | |
5 | |
265 | 6 use IMPL::Const qw(:prop); |
7 use IMPL::declare { | |
8 require => { | |
9 Provider => 'Template::Provider', | |
10 Context => 'Template::Context', | |
309 | 11 TTRegistry => 'IMPL::Web::View::TTRegistry', |
308 | 12 TTFactory => 'IMPL::Web::View::TTFactory', |
309 | 13 TTDocument => '-IMPL::Web::View::TTDocument', |
265 | 14 Exception => 'IMPL::Exception', |
15 ArgumentException => '-IMPL::InvalidArgumentException', | |
16 KeyNotFoundException => '-IMPL::KeyNotFoundException' | |
17 }, | |
18 base => [ | |
19 'IMPL::Object' => undef, | |
20 'IMPL::Object::Serializable' => undef | |
21 ], | |
22 props => [ | |
23 options => PROP_RO, | |
24 provider => PROP_RO, | |
25 context => PROP_RO, | |
26 ext => PROP_RO, | |
27 layoutBase => PROP_RO, | |
28 isInitialized => PROP_RO, | |
29 initializer => PROP_RO, | |
30 _globals => PROP_RW | |
31 ] | |
32 }; | |
181 | 33 |
196 | 34 sub save { |
35 my ($this,$context) = @_; | |
36 | |
37 $context->AddVar($_, $this->$_()) for qw(options provider context ext layoutBase); | |
38 } | |
39 | |
40 sub restore { | |
41 my ($class,$data,$surrogate) = @_; | |
42 | |
43 my %params = @$data; | |
44 | |
45 my $refOpts = delete $params{options}; | |
46 | |
47 if ($surrogate){ | |
48 $surrogate->callCTOR($refOpts,%params); | |
49 } else { | |
50 $surrogate = $class->new($refOpts,%params); | |
51 } | |
206 | 52 return $surrogate; |
196 | 53 } |
54 | |
181 | 55 sub CTOR { |
194 | 56 my ($this,$refOpts,%args) = @_; |
57 | |
58 $refOpts ||= {}; | |
59 | |
60 $this->ext($args{ext}) if $args{ext}; | |
61 $this->initializer($args{initializer}) if $args{initializer}; | |
62 $this->_globals(ref $args{globals} eq 'HASH' ? $args{globals} : {}); | |
63 | |
64 $this->options($refOpts); | |
195
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
65 $this->layoutBase($args{layoutBase}) if $args{layoutBase}; |
194 | 66 |
67 # to aviod cyclic references we need to do a copy of $refOpts | |
265 | 68 $refOpts->{LOAD_TEMPLATES} = $this->provider(Provider->new( { %$refOpts } )); |
194 | 69 |
265 | 70 $this->context(Context->new($refOpts)); |
181 | 71 } |
72 | |
73 sub document { | |
194 | 74 my ($this,$name,$vars) = @_; |
75 | |
309 | 76 $vars ||= {}; |
308 | 77 |
194 | 78 my $tt = $this->template($name); |
79 | |
80 $this->_init(); | |
81 | |
82 my $opts = { %{ $this->options } }; | |
83 | |
287 | 84 $this->context->localise(); |
289 | 85 my $ctx = _clone_context($this->context); |
287 | 86 $this->context->delocalise(); |
194 | 87 |
309 | 88 my $registry = TTRegistry->new($this, $ctx); |
89 | |
90 my $factory = TTFactory->new($tt->class || TTDocument, $tt, $ctx, $name, $registry); | |
308 | 91 |
309 | 92 $vars->{registry} = $registry; |
93 | |
94 return $factory->new( $vars ); | |
181 | 95 } |
96 | |
308 | 97 |
181 | 98 sub template { |
194 | 99 my ($this,$name) = @_; |
100 | |
101 $name =~ s/^\s+|\s+$//g; | |
102 | |
265 | 103 die ArgumentException->new("A valid template name is required") unless length $name; |
194 | 104 |
105 $name = $this->_appendExt($name); | |
106 | |
107 my ($tt,$error) = $this->provider->fetch($name); | |
108 | |
109 if (defined $error and $error == STATUS_DECLINED) { | |
285
546957c50a36
*IMPL::Web::Handler::TTView Reworked template selection mechanism
cin
parents:
265
diff
changeset
|
110 die KeyNotFoundException->new($name); |
194 | 111 } elsif (defined $error and $error == STATUS_ERROR) { |
265 | 112 die Exception->new("Failed to load a template", $name, $tt); |
194 | 113 } |
114 | |
115 return $tt; | |
181 | 116 } |
117 | |
195
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
118 sub layout { |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
119 my ($this,$name) = @_; |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
120 |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
121 my $layout; |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
122 |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
123 if ($this->layoutBase) { |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
124 $layout = $this->layoutBase . "/"; |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
125 } |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
126 |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
127 $layout .= $name; |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
128 return $this->template($layout); |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
129 } |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
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 |