Mercurial > pub > Impl
annotate Lib/IMPL/Web/View/TTLoader.pm @ 303:a5eb64c6e6f7
TTDocument.GetTemplate corrected to work with document blocks
author | cin |
---|---|
date | Mon, 08 Apr 2013 02:18:47 +0400 |
parents | 85572f512abc |
children | 47a09a8dc23a |
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', | |
11 TTDocument => 'IMPL::Web::View::TTDocument', | |
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 | |
74 my $tt = $this->template($name); | |
75 | |
76 $this->_init(); | |
77 | |
78 my $opts = { %{ $this->options } }; | |
79 | |
287 | 80 $this->context->localise(); |
289 | 81 my $ctx = _clone_context($this->context); |
287 | 82 $this->context->delocalise(); |
194 | 83 |
287 | 84 return TTDocument->new( $tt, $ctx, $this, $vars ); |
181 | 85 } |
86 | |
87 sub template { | |
194 | 88 my ($this,$name) = @_; |
89 | |
90 $name =~ s/^\s+|\s+$//g; | |
91 | |
265 | 92 die ArgumentException->new("A valid template name is required") unless length $name; |
194 | 93 |
94 $name = $this->_appendExt($name); | |
95 | |
96 my ($tt,$error) = $this->provider->fetch($name); | |
97 | |
98 if (defined $error and $error == STATUS_DECLINED) { | |
285
546957c50a36
*IMPL::Web::Handler::TTView Reworked template selection mechanism
cin
parents:
265
diff
changeset
|
99 die KeyNotFoundException->new($name); |
194 | 100 } elsif (defined $error and $error == STATUS_ERROR) { |
265 | 101 die Exception->new("Failed to load a template", $name, $tt); |
194 | 102 } |
103 | |
104 return $tt; | |
181 | 105 } |
106 | |
195
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
107 sub layout { |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
108 my ($this,$name) = @_; |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
109 |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
110 my $layout; |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
111 |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
112 if ($this->layoutBase) { |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
113 $layout = $this->layoutBase . "/"; |
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 |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
116 $layout .= $name; |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
117 return $this->template($layout); |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
118 } |
7a920771fd8e
IMPL::Web::View changed document layout handling, docs, examples
cin
parents:
194
diff
changeset
|
119 |
181 | 120 sub _appendExt { |
194 | 121 my ($this,$name) = @_; |
122 | |
123 return $name unless $this->ext; | |
124 | |
125 if (length $this->ext and substr( $name, -length($this->ext) ) eq $this->ext) { | |
126 return $name; | |
127 } else { | |
128 return $name . $this->ext; | |
129 } | |
181 | 130 } |
131 | |
132 sub _init { | |
194 | 133 my ($this) = @_; |
134 | |
135 if (!$this->isInitialized) { | |
136 my $initializer = $this->initializer || sub {}; | |
137 | |
138 eval { | |
139 $this->context->process($initializer,$this->_globals); | |
140 }; | |
141 if (my $e = $@) { | |
265 | 142 die Exception->new("Failed to process an initializer", $this->initializer, $e); |
194 | 143 } |
144 | |
145 $this->isInitialized(1); | |
146 } | |
181 | 147 } |
148 | |
289 | 149 sub _clone_context { |
150 my $args = { %{shift || {}} }; | |
151 delete $args->{CONFIG}; | |
152 | |
153 return Template::Context->new($args); | |
154 } | |
155 | |
181 | 156 1; |
157 | |
158 __END__ | |
159 | |
160 =pod | |
161 | |
162 =head1 NAME | |
163 | |
164 C<IMPL::Web::View::TTLoader> - предоставляет глобальный контекст для загрузки шаблонов | |
165 | |
166 =head1 SYNOPSIS | |
167 | |
168 =begin code | |
169 | |
170 use IMPL::Web::View::TTLoader(); | |
171 | |
172 my $loader = new IMPL::Web::View::TTLoader( | |
194 | 173 { |
174 INCLUDE_PATH => [ | |
175 '/my/app/tt', | |
176 '/my/app/tt/lib' | |
177 ] | |
178 }, | |
179 ext => '.tt', | |
180 initializer => 'shared/global' | |
181 | |
181 | 182 ); |
183 | |
184 my $doc = $loader->document('index'); | |
185 | |
186 my $html = $doc->Render(); | |
187 | |
188 =end code | |
189 | |
190 =head1 DESCRIPTION | |
191 | |
265 | 192 Провайдер для загрузки шаблонов и документов. Имеет собственное пространство |
193 имен, контекст выполнения шаблонов. Контект загрузчика инициализируется | |
194 шаблоном, в котором определяются глобальные переменные, которые будут доступны | |
195 в документах, однако их изменения будут локализованы. | |
196 | |
197 Инициализация контекста провайдера происходит при первой загрузке любого | |
198 документа. | |
199 | |
182 | 200 =head1 MEMBERS |
201 | |
265 | 202 =head2 C<CTOR($options,%args)> |
203 | |
204 =over | |
205 | |
206 =item * C<$options> | |
207 | |
208 Параметры контекста загрузчика, контексты документов и элементов управления | |
209 также унаследуют эти свойства. Напрямую передаются в конструктор | |
210 C<Template::Context>. | |
211 | |
212 =item * C<%args> | |
213 | |
214 Именованные параметы загрузчика. | |
215 | |
216 =over | |
217 | |
218 =item * C<ext> | |
219 | |
220 Расширение, которое будет добавляться к именам шаблонов и документов (если оно | |
221 не будет указано явно). | |
222 | |
223 =item * C<initializer> | |
224 | |
225 Имя шаблона, который будет использован для инициализации контекста. | |
226 | |
227 =item * C<globals> | |
228 | |
229 Глобальные переменнын, которые будут переданы в контекст. | |
230 | |
231 =item * C<layoutBase> | |
232 | |
233 Путь к шаблонам для оформления документов. Каждый документ может задавать свой | |
234 C<layout> указанный в его C<META> блоке или конструкторе. | |
235 См. C<IMPL::View::TTDocument>. | |
236 | |
237 =back | |
238 | |
239 =back | |
240 | |
182 | 241 =head2 C<document($docName)> |
242 | |
265 | 243 Загружает документ с именем C<$docName>. При необходимости к нему будет |
244 добавлено расширение, указанное в свойстве C<ext>. Это единственно полезный | |
245 метод провайдера. | |
246 | |
181 | 247 =cut |
248 |