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