]> git.decadent.org.uk Git - maypole.git/blob - doc/View.pod
7ce7af38506a18e6bc8b797a0cd98c38eac074fc
[maypole.git] / doc / View.pod
1 =head1 Maypole View Classes
2
3 In a large application, you will almost certainly want to customize the
4 layout and design of the output pages. This task may even be the purview
5 of a separate team of HTML designers rather than the programmers. Since
6 a typical programmer will try to avoid touching HTML as much as possible
7 and a typical designer will try to avoid touching Perl code, programmers
8 have evolved a system of templating to separate the concerns of
9 programming and designing. 
10
11 One of the core concepts in Maypole is the I<view class>, and this is
12 responsible for routing the data produced in the model class into the
13 templates produced by the designers. Of course, there are a great many
14 possible templating systems and styles, and so there can be a great many
15 possible Maypole view classes. Each view class will take the data from
16 the controller, locate a template to be processed, and hand the whole
17 lot to its preferred templating module, which will then do the hard work
18 of filling in the template and coming up with the output.
19
20 You can choose whatever Maypole view class you want, but the default
21 view class is C<Maypole::View::TT>, and it feeds its data and templates
22 to a module called the Template Toolkit.
23
24 =head2 The Template Toolkit
25
26 The Template Toolkit, written by Andy Wardley, is a very powerful and
27 generic templating system. It provides its own little formatting language
28 which supports loops, conditionals, hash and array dereferences and
29 method calls, macro processing and a plug-in system to connect it to
30 external Perl modules. There are several good introductions to the
31 Template Toolkit available: you should have one installed as
32 L<Template::Tutorial::Datafile>; there's one at
33 L<http://www.perl.com/pub/a/2003/07/15/nocode.html>, and of course
34 there's the "Badger Book" - I<The Perl Template Toolkit>, by Andy et al.
35
36 We'll present a brief introduction here by deconstructing some of the 
37 templates used by Maypole applications. For more deconstruction, see
38 L<StandardTemplates.pod>, which is an entire chapter dealing with the
39 factory supplied templates.
40
41 Here's the template which is called for the front page of the standard
42 beer database application, C<custom/frontpage>.
43
44     [% INCLUDE header %]
45
46     <h2> The beer database </h2>
47
48     <TABLE BORDER="0" ALIGN="center" WIDTH="70%">
49     [% FOR table = config.display_tables %]
50     <TR>
51     <TD>
52     <A HREF="[%table%]/list">List by [%table %]</A>
53     </TD>
54     </TR>
55     [% END %]
56     </TABLE>
57
58 The first thing to note about this is that everything outside of the
59 Template Toolkit tags (C<[%> and C<%]>) is output verbatim. That is,
60 you're guaranteed to see 
61
62     <h2> The beer database </h2>
63
64     <TABLE BORDER="0" ALIGN="center" WIDTH="70%">
65
66 in the output somewhere. Inside the tags, magic happens. The first piece
67 of magic is the C<[% INCLUDE header %]> directive. This goes away and
68 finds a file called F<header> - don't worry about how it finds that yet,
69 we'll come to that later on - and processes the file's contents as
70 though they were right there in the template. Our F<header> file happens
71 not to contain any C<[% %]> tags, but if it did, they would be processed
72 in the same way as the ones in F<frontpage>. 
73
74 The next piece of magic is this line:
75
76     [% FOR table = config.display_tables %]
77
78 We're seeing a lot of things here at once. C<config> is where we should
79 start looking. This is a template variable, which is what templates are
80 all about - templating means getting data from somewhere outside and
81 presenting it to the user in a useful way, and the C<config> hash is a
82 prime example of data that we want to use. It's actually the hash of
83 configuration parameters for this Maypole application, and one of the
84 keys in that hash is C<display_tables>, the database tables that we're
85 allowed to play with. In the application, we probably said something
86 like
87
88     BeerDB->config->{display_tables} = [qw[beer brewery pub style]];
89
90 This stores the four values - C<beer>, C<brewery>, C<pub> and C<style> -
91 in an array, which is placed in the config hash under the key
92 C<display_tables>. Now we're getting them back again.
93
94 The Template Toolkit's dot operator is a sort of do-the-right-thing
95 operator; we can say C<array.0> to get the first element of an array,
96 C<hash.key> to look up the C<key> key in a hash, and C<object.method> to
97 call C<method> on an object. So, for instance, if we said
98 C<config.display_tables.2>, we'd look up the C<display_tables> key in
99 the configuration hash and get our array back, then look up the 2nd
100 element and get C<pub>.
101
102 The C<FOR> loop will repeat the code four times, setting our new
103 variable C<table> to the appropriate array element. This code:
104
105     [% FOR table = config.display_tables %]
106         Hello [% table %]!
107     [% END %]
108
109 will produce something like
110
111     Hello beer!
112     Hello brewery!
113     Hello pub!
114     Hello style!
115
116 In our case, though, we're printing out a table element linking to each
117 database table in turn.
118
119 Here's a slightly more complicated example, adapted from F<factory/pager>.
120 This template is responsible for printing the little page menu at the
121 bottom of a listing if there are more rows in the listing than we want
122 on a single page.
123
124     [% PROCESS macros %]
125     <P ALIGN="center">Pages:
126     [%
127          FOREACH num = [pager.first_page .. pager.last_page];
128               IF num == pager.current_page;
129                 "["; num; "] ";
130               ELSE;
131                 SET args = "?page=" _ num;
132                 SET label = "[" _ num _ "]";
133                 link(classmetadata.moniker, "list", args, label);
134               END;
135          END;
136     %]
137     </P>
138
139 Maypole will be providing a whole bunch of variables to this template,
140 and we'll look at them all in a moment, but the only ones we need to care
141 about are C<pager> and C<classmetadata>. 
142
143 We start by loading in a bunch of macros. Macros are Template Toolkit's
144 functions - you can provide them some parameters and they'll run a little
145 sub-template based on them. The C<macros> file contains some handy macros
146 that I've found useful for constructing Maypole templates; again, these
147 will be covered in full detail in L<StandardTemplates.pod>.
148
149 We're going to be displaying something like this:
150
151     Pages: [1] [2] [3] [4]
152
153 with most of those numbers being a link to the appropriate page. This
154 mean we're going to have to have a list of numbers, and the C<FOREACH> loop
155 provides this: (C<FOREACH> and C<FOR> are identical, just like in Perl.)
156
157          FOREACH num = [pager.first_page .. pager.last_page];
158
159 Here we're manually constructing an array of numbers, using the range
160 operator (C<..>) to fill in all the numbers from the C<first_page> (1)
161 to the C<last_page> (4). The same dot operator is used to ask the C<pager>
162 what its C<first_page> and C<last_page> is. Remember when we said 
163 C<config.display_tables>, we were looking up the C<display_tables> key
164 in the C<config> hash? Well, this time we're not looking anything up in
165 a hash. C<pager> is an object, and C<first_page> is a method. Thing is,
166 you don't have to care. You can pretend it's a hash if you want. The
167 syntax is the same, and Template Toolkit knows the right thing to do.
168
169 Now we're going to be executing this loop four times, once each for C<num>
170 being set to 1, 2, 3, and 4. At some point, we'll come across the page
171 that we're actually on right now:
172
173       IF num == pager.current_page;
174
175 and in that case, we don't want to produce a link to it. We just want
176 to output it as text, surrounded by square brackets:
177
178                 "["; num; "] ";
179
180 We're using string literals to output the brackets. We don't have to
181 do that. We could say it this way:
182
183     [% ...
184       IF num == pager.current_page;
185     %]
186         [ [% num %] ] 
187     [% ELSE %]
188        ...
189     [% END %]
190
191 But you know, I quite like it my way.
192
193 Now if the number we're printing isn't the number of the current page,
194 we want to make a link. Here's how we do it:
195
196     SET args = "?page=" _ num;
197     SET label = "[" _ num _ "]";
198     link(classmetadata.table, "list", args, label);
199
200 C<SET> declares a new variable of our own. If there was anything called
201 C<args> before, there isn't now. It's going to be the result of our
202 statement C<"?page=" _ num>. C<_> is the concatenation operator, and
203 glues C<?page=> onto the front of our number. So if we want to link to
204 page 4, then the C<args> variable will contain C<?page=4>. Similarly,
205 the C<label> variable will be C<[4]>.
206
207 Now we call a macro, C<link> with these two variables and the value of
208 C<classmetadata.table>. This macro takes four arguments, C<table>, 
209 C<action>, C<args> and C<label>, and constructs a link of the form
210
211     <A HREF="[% config.base_url %]/[% table %]/[% action %][% args %]">
212     [% label %]
213     </A>
214
215 In our case, it'll be filled in like so:
216
217     <A HREF="[% config.base_url %]/[% classmetadata.table %]/list?page=4">
218     [ 4 ]
219     </A>
220
221 Where C<classmetadata.table> will actually be the name of the current
222 table, and C<config.base_url> will be replaced by the appropriate URL for
223 this application. But where do these values, C<config> and C<classmetadata>,
224 come from, and what else can we do with them?
225
226 =head2 What Maypole provides to a template
227
228 XXX
229
230 =head2 Maypole::View::TT and other view classes
231
232 Please note that these template variables, C<config>, C<classmetadata>,
233 C<objects> and its user-friendly alias, as well as the rest of themm are
234 a function of one particular view class, the default
235 C<Maypole::View::TT> class. Other view classes may need to present an
236 entirely different set of template variables, since the default ones
237 might not make sense. The templates may look wildly different in other
238 view class implementations. But that's OK, because you couldn't
239 necessarily use the same templates with a different templating system
240 anyway.
241
242 For instance, in really dumb templating languages which can't handle
243 dereferencing hashes or arrays - no wait, that's most of them - passing
244 in a hash reference like C<classmetadata> won't help you since you can't
245 get at any of its elements. So you'll need to take a look at the
246 documentation for the appropriate view class to see what template
247 variables it provides.
248
249 Another feture of C<Maypole::View::TT> which may not be present in
250 alternate view class implementations - although they are strongly
251 encouraged to provide it - is the way that templates are located.
252 (Remember, I B<did> say I'd tell you about that later.) Template Toolkit
253 allows whatever uses it to provide a path for template files to be
254 located in. C<Maypole::View::TT> feeds it up to three possible
255 directories to look things up in, and it will try to find a template in
256 each of these in turn.
257
258 When you configure a Maypole application, you can tell it the base
259 directory of your templates like so:
260
261     BeerDB->config->{template_root} = "/var/www/beerdb/templates";
262
263 If you don't do this, most Maypole front-ends will use the current
264 directory, which is generally what you want anyway. Off this directory,
265 Maypole will look for a set of subdirectories.
266
267 For instance, I said we were in the middle of processing the front page
268 and looking up a template file called F<header>. Maypole will first look
269 for this file in the F<custom> subdirectory. (say,
270 F</var/www/beerdb/templates/custom>) If it doesn't find one, then it
271 looks in the F<factory> subdirectory. If it doesn't find one there, then
272 it gives up and dies with an error. But that's your fault, since you've
273 called for a template which doesn't exist. Don't do that. 
274
275 This behaviour means that you can provide your own site-specific
276 templates, but if you don't do so, then you get to use a generic one
277 provided by Maypole. Maypole's "factory setting" templates are written
278 in such a way as to try and do the right thing no matter what your
279 application does. They are occasionally successful at this. 
280
281 Now the front page was a pretty simple example, since Maypole only looks
282 up two directories. In most cases, it checks an additional directory,
283 and this directory depends entirely on what Maypole is doing.
284
285 If you're writing an e-commerce application, for example, you may well
286 have a table which represents the product catalogue and all the products
287 you can buy. Let's call this the C<product> table. You'll also have a
288 data source which is specific to the user which contains all the
289 products that they're buying on this particular visit to the site. In
290 time-honoured tradition, we'll call this the C<basket> table.
291
292 Now it ought to be reasonably apparent that you don't want the basket
293 to be displayed in exactly the same way as the product catalogue. The
294 templates for C<product/list> and C<basket/list> need to be different.
295 This is where the third directory comes in. The other directory, which
296 Maypole checks very first of all, is specific to the table that you're
297 viewing. So if you go to C<http://your.shop.com/basket/list>, Maypole
298 will look in the F<basket> directory first for a file called F<list>,
299 and second in the F<custom> directory for a site-wide list template,
300 and then fall-back to the F<factory> directory for a generic list
301 template. It should be obvious that you probably want to provide all
302 of F<basket/list>, F<basket/view>, F<product/list>, F<product/view>
303 and any other combination of classes and actions that you can think of.
304
305 Again, this only goes for C<Maypole::View::TT>. If, for some perverse
306 reason, the Template Toolkit just isn't good enough for you, then you
307 can set your own view class while configuring your application:
308
309    package BeerDB;
310    use base 'Apache::MVC';
311    ...
312    BeerDB->setup("dbi:SQLite:t/beerdb.db");
313    BeerDB->config->{uri_base} = "http://localhost/beerdb/";
314    BeerDB->config->{rows_per_page} = 10;
315    BeerDB->config->{view} = "Maypole::View::Mason"; 
316
317 Where do these alternate view classes come from? Gentle reader, they
318 come from B<you>.
319
320 =head2 Building your own view class
321
322 I<You should probably skip this section for the first few readings of this manual. It's only intended for people extending Maypole.>
323
324 Imagine you've found a brand new templating system that's B<much better>
325 than the Template Toolkit. I know I'm stretching your imagination a bit
326 here, but try. You'd like to use it with Maypole, which means writing your
327 own view class. How is it done?
328
329 We'll demonstrate by implementing a view class for C<HTML::Mason>,
330 although no value judgement is implied. C<HTML::Mason> is a templating
331 system which embeds pure Perl code inside its magic tags. The good side
332 of this is that it can get into hash references and objects, and so
333 providing C<classmetadata>, C<config> and the Maypole request object
334 will work out just fine. The down side is that C<HTML::Mason> is used to
335 having all the template variables it wants already at its disposal
336 through CGI parameters and the like, so we have to fiddle a bit to get
337 these variables into our template.
338
339 XXX