]> git.decadent.org.uk Git - maypole.git/blob - lib/Maypole/View/TT.pm
AJT synch
[maypole.git] / lib / Maypole / View / TT.pm
1 package Maypole::View::TT;
2 use base 'Maypole::View::Base';
3 use Maypole::Constants;
4 use Template;
5 use File::Spec::Functions qw(catdir tmpdir);
6
7 our $error_template; 
8 { local $/; $error_template = <DATA>; }
9
10 use strict;
11 our $VERSION = 2.11;
12
13 sub template {
14     my ( $self, $r ) = @_;
15
16     unless ($self->{tt}) {
17         my $view_options = $r->config->view_options || {};
18         $self->{provider} = Template::Provider->new($view_options);
19         $self->{tt}       = Template->new({
20             %$view_options,
21             LOAD_TEMPLATES => [ $self->{provider} ],
22         });
23     }
24
25     $self->{provider}->include_path([ $self->paths($r) ]);
26
27     my $template_file = $r->template;
28     my $ext = $r->config->template_extension;
29     $template_file .= $ext if defined $ext;
30
31     my $output;
32     if ($self->{tt}->process($template_file, { $self->vars($r) }, \$output )) {
33         $r->{output} = $output;
34         return OK;
35     }
36     else {
37         $r->{error} = "TT error for template '$template_file'\n" . $self->{tt}->error;
38         return ERROR;
39     }
40 }
41
42
43 sub report_error {
44     my ($self, $r, $error, $type) = @_;
45     my $output;
46     # Need to be very careful here.
47     my $tt = Template->new;
48     if ($tt->process(\$error_template,
49         { err_type => $type, error => $error, 
50          config => { %{$r->{config}}},
51           request => $r, # We have that at least
52         eval{$self->vars($r)} }, \$output )) {
53         $r->{output} = $output;
54         if ($tt->error) { $r->{output} = "<html><body>Even the error template
55         errored - ".$tt->error."</body></html>"; }
56         $r->{content_type}      ||= "text/html";
57         $r->{document_encoding} ||= "utf-8";
58         return OK;
59     }
60     return ERROR;
61 }
62
63
64 =head1 NAME
65
66 Maypole::View::TT - A Template Toolkit view class for Maypole
67
68 =head1 SYNOPSIS
69
70     BeerDB->config->view("Maypole::View::TT"); # The default anyway
71
72     # Set some Template Toolkit options
73     BeerDB->config->view_options( {
74         TRIM        => 1,
75         COMPILE_DIR => '/var/tmp/mysite/templates',
76     } );
77
78     .....
79
80     [% PROCESS macros %]
81
82     [% pager %]
83
84     [% link %]
85
86     [% maybe_link_view %]
87
88 =head1 DESCRIPTION
89
90 This is the default view class for Maypole; it uses the Template Toolkit to fill
91 in templates with the objects produced by Maypole's model classes. Please see
92 the L<Maypole manual|Maypole::Manual>, and in particular, the
93 L<view|Maypole::Manual::View> chapter for the template variables available and
94 for a refresher on how template components are resolved.
95
96 The underlying Template toolkit object is configured through
97 C<$r-E<gt>config-E<gt>view_options>. See L<Template|Template> for available
98 options.
99
100 =over 4
101
102 =item template
103
104 Processes the template and sets the output. See L<Maypole::View::Base>
105
106 =back
107
108 =head1 TEMPLATE TOOLKIT INTRODUCTION
109
110 The Template Toolkit uses it's own mini language described in
111 L<Template::Manual::Directives>.
112
113 A simple example would be :
114
115 =over 4
116
117 re:[% subject %]
118
119 Dear [% title %] [% surname %],
120 Thank you for your letter dated [% your.date %]. This is to
121 confirm that we have received it and will respond with a more
122 detailed response as soon as possible. In the mean time, we
123 enclose more details of ...
124
125 =back
126
127 TT uses '[%' and '%]' (by default) to delimit directives within a template, and
128 the simple directives above just display the value of variable named within
129 those delimiters -- [% title %] will be replaced inline with the value of the
130 'title' variable passed in the 'stash' to the template when it is processed.
131
132 You can access nested data through the dot ('.') operator, which will
133 dereference array or hash elements, but can also be used to call methods on
134 objects, i.e. '[% name.salutation("Dear %s,") %]'. The other main operator is
135 underscore ('_'), which will concatonate strings or variables.
136
137 The value returned by a directive replaces the directive inline when the
138 template is processes, you can also SET a value which will not return anything,
139 or CALL a method or operation which will also not return anything.
140
141 You can specify expressions using the logical (and, or, not, ?:) and mathematic
142 operators (+ - * / % mod div).
143
144 =over 4
145
146 [% template.title or default.title %]
147
148 [% score * 100 %]
149
150 [% order.nitems ? checkout(order.total) : 'no items' %]
151
152 =back
153
154 TT allows you to include or re-use templates through it's INCLUDE, PROCESS and
155 INSERT directives, which are fairly self explainatory. You can also re-use parts
156 of template with the BLOCK or MACRO directives.
157
158 Conditional and Looping constructs are simple and powerful, and TT provides an
159 inbuilt iterator and helper functions and classes that make life sweet.
160
161 Conditional directives are IF, UNLESS, ELSIF, ELSE and behave as they would in
162 perl :
163
164 =over 4
165
166 [% IF age < 10 %]
167   Hello [% name %], does your mother know you're  using her AOL account?
168 [% ELSIF age < 18 %]
169   Sorry, you're not old enough to enter (and too dumb to lie about your age)
170 [% ELSE %]
171   Welcome [% name %].
172 [% END %]
173
174 [% UNLESS text_mode %] [% INCLUDE biglogo %] [% END %]
175
176 =back
177
178 Looping directives are FOREACH, LAST and BREAK.
179
180 FOREACH loops through a HASH or ARRAY processing the enclosed block for each
181 element.
182
183 Looping through an array
184
185  [% FOREACH i = items %]
186  [% i %]
187  [% END %]
188
189 Looping through a hash
190
191  [% FOREACH u IN users %]
192  * [% u.key %] : [% u.value %]
193  [% END %]
194
195 Looping through an array of hashes
196
197  [% FOREACH user IN userlist %]
198  * [% user.id %] [% user.name %]
199  [% END %]
200
201 The LAST and BREAK directive can be used to exit the loop.
202
203 The FOREACH directive is implemented using the Template::Iterator module. A
204 reference to the iterator object for a FOREACH directive is implicitly available
205 in the 'loop' variable. The loop iterator object provides a selection of methods
206 including size(), max(), first(), last(), count(), etc
207
208 =over 4
209
210   [% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%]
211     [%- "<ul>\n" IF loop.first %]
212       <li>[% loop.count %]/[% loop.size %]: [% item %]
213     [%- "</ul>\n" IF loop.last %]
214   [% END %]
215
216 =back
217
218 See Template::Iterator for further details on looping and the Iterator.
219
220 You might notice the minus ('-') operator in the example above, it is used to
221 remove a newline before or after a directive so that you can layout the Template
222 logic as above but the resulting output will look exactly how you require it.
223
224 You will also frequently see comments and multi-line directives, # at the start
225 of a directive marks it as a comment, i.e. '[%# this is a comment %]'. A
226 multiline directive looks like :
227
228  [% do.this;
229     do.that;
230     do.the_other %]
231
232 You can see that lines are terminated with a semi-colon (';') unless the
233 delimter ('%]') closes the directive.
234
235 For full details of the Template Toolkit see Template::Manual and
236 Template::Manual::Directives, you can also check the website, mailing list or
237 the Template Toolkit book published by O Reilly.
238
239 =head1 TEMPLATE PLUGINS, FILTERS AND MACROS
240
241 The Template Toolkit has a popular and powerful selection of Plugins and
242 Filters.
243
244 TT Plugins provide additional functionality within Templates, from accessing CGI
245 and databases directly, handling paging or simple integration with Class::DBI
246 (for those rare occasions where you don't actually need Maypole). See
247 L<Template::Manual::Plugins>.
248
249 One plugin that is indispensible when using Maypole and the Template View is
250 C<Template::Plugin::Class> -- This allows you to import and use any class
251 installed within a template. For example :
252
253 =over 4
254
255 [% USE foo = Class('Foo') %]
256 [% foo.bar %]
257
258 =back
259
260 Would do the equivilent of 'use Foo; Foo->bar;' in perl. See
261 L<Template::Plugin::Class> for details.
262
263 TT Filters process strings or blocks within a template, allowing you to
264 truncate, format, escape or encode trivially. A useful selection is included
265 with Template Toolkit and they can also be found on CPAN or can be written
266 easily. See L<Template::Manual::Filters>.
267
268 TT Macros allow you to reuse small blocks of content, directives, etc. The MACRO
269 directive allows you to define a directive or directive block which is then
270 evaluated each time the macro is called. Macros can be passed named parameters
271 when called.
272
273 Once a MACRO is defined within a template or 'include'd template it can be used
274 as if it were a native TT directive. Maypole provides a selection of powerful
275 and useful macros in the templates/ directory of the package and these are used
276 in the beerdb and default templates. See the MACRO section of the
277 L<Template::Manual::Directives> documentation.
278
279 =head1 ACCESSING MAYPOLE VALUES
280
281 =head2 request
282
283 You can access the request in your templates in order to see the action, table, etc as well
284 as parameters passed through forms :
285
286 for example
287
288 Hello [% request.params.forename %] [% request.params.surname %] !
289
290 or 
291
292 Are you want to [% request.action %] in the [% request.table %] ?
293
294 =head2 config
295
296 You can access your maypole application configuration through the config variable :
297
298 <link base="[% config.uri_base %]"/>
299
300 =head2 object and objects
301
302 Objects are passed to the request using r->objects($arrayref) and are accessed in the templates
303 as an array called objects.
304
305 [% FOR objects %] <a href="[% config.uri_base %]/[% request.table %]/view/[% object.id %]"> [% object %] </a> [% END %]
306
307 =head1 MAYPOLE MACROS AND FILTERS
308
309 Maypole provides a collection of useful and powerful macros in the templates/factory/macros
310  and other templates. These can be used in any template with [% PROCESS templatename %].
311
312 =head2 link
313
314 This creates an <A HREF="..."> to a command in the Apache::MVC system by
315 catenating the base URL, table, command, and any arguments.
316
317 =head2 maybe_link_view
318
319 C<maybe_link_view> takes something returned from the database - either
320 some ordinary data, or an object in a related class expanded by a
321 has-a relationship. If it is an object, it constructs a link to the view
322 command for that object. Otherwise, it just displays the data.
323
324 =head2 pager
325
326 This is an include template rather than a macro, and it controls the pager
327 display at the bottom (by default) of the factory list and search views/template.
328 It expects a C<pager> template argument which responds to the L<Data::Page> interface.
329
330 This macro is in the pager template and used as :
331
332 [% PROCESS pager %]
333
334 Maypole provides a pager for list and search actions, otherwise you can
335 provide a pager in the template using Template::Plugin::Pagination.
336
337 [% USE pager = Pagination(objects, page.current, page.rows) %]
338 ...
339 [% PROCESS pager %]
340
341 The pager will use a the request action  as the action in the url unless the
342 pager_action variable is set, which it will use instead if available.
343
344 =head2 other macros
345
346 =head1 AUTHOR
347
348 Simon Cozens
349
350 =cut
351
352 1;
353
354 __DATA__
355 <html><head><title>Maypole error page</title>
356 <style type="text/css">
357 body { background-color:#7d95b5; font-family: sans-serif}
358 p { background-color: #fff; padding: 5px; }
359 pre { background-color: #fff; padding: 5px; border: 1px dotted black }
360 h1 { color: #fff }
361 h2 { color: #fff }
362 .lhs {background-color: #ffd; }
363 .rhs {background-color: #dff; }
364 </style>
365 </head> <body>
366 <h1> Maypole application error </h1>
367
368 <p> This application living at <code>[%request.config.uri_base%]</code>, 
369 [%request.config.application_name || "which is unnamed" %], has
370 produced an error. The adminstrator should be able to understand
371 this error message and fix the problem.</p>
372
373 <h2> Some basic facts </h2>
374
375 <p> The error was found in the [% err_type %] stage of processing
376 the path "[% request.path %]". The error text returned was:
377 </p>
378 <pre>
379     [% error %]
380 </pre>
381
382 <h2> Request details </h2>
383
384 <table> 
385     [% FOR thing = ["model_class", "table", "template", "path",
386     "content_type", "document_encoding", "action", "args", "objects"] %]
387     <tr> <td class="lhs"> [%thing %] </td> <td class="rhs"> [%
388     request.$thing.list.join(" , ") %] </td></tr>
389     [% END %]
390 </table>
391
392 <h2> Application configuration </h2>
393 <table> 
394     [% FOR thing = config.keys %]
395     <tr> <td class="lhs"> [%thing %] </td> <td class="rhs"> [% 
396     config.$thing.list.join(" , ") %] </td></tr>
397     [% END %]
398 </table>
399
400 </body>
401 </html>
402
403