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