Commit | Line | Data |
3fea05b9 |
1 | #============================================================= -*-perl-*- |
2 | # |
3 | # Template::Manual::VMethods |
4 | # |
5 | # AUTHOR |
6 | # Andy Wardley <abw@wardley.org> |
7 | # |
8 | # COPYRIGHT |
9 | # Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved. |
10 | # |
11 | # This module is free software; you can redistribute it and/or |
12 | # modify it under the same terms as Perl itself. |
13 | # |
14 | #======================================================================== |
15 | |
16 | =head1 NAME |
17 | |
18 | Template::Manual::VMethods - Virtual Methods |
19 | |
20 | =head1 Scalar Virtual Methods |
21 | |
22 | =head2 defined |
23 | |
24 | Returns true if the value is defined. |
25 | |
26 | [% user = get_user(uid) IF uid.defined %] |
27 | |
28 | =head2 length |
29 | |
30 | Returns the length of the string representation of the item: |
31 | |
32 | [% IF password.length < 8 %] |
33 | Password too short, dumbass! |
34 | [% END %] |
35 | |
36 | =head2 repeat(n) |
37 | |
38 | Repeat the string a specified number of times. |
39 | |
40 | [% name = 'foo' %] |
41 | [% name.repeat(3) %] # foofoofoo |
42 | |
43 | =head2 replace(search, replace) |
44 | |
45 | Outputs the string with all instances of the first argument (specified |
46 | as a Perl regular expression) with the second. |
47 | |
48 | [% name = 'foo, bar & baz' %] |
49 | [% name.replace('\W+', '_') %] # foo_bar_baz |
50 | |
51 | You can use C<$1>, C<$2>, etc., to reference captured parts (in parentheses) |
52 | in the regular expression. Just be careful to I<single> quote the replacement |
53 | string. If you use I<double> quotes then TT will try and interpolate the |
54 | variables before passing the string to the C<replace> vmethod. |
55 | |
56 | [% name = 'FooBarBaz' %] |
57 | [% name.replace('([A-Z])', ' $1') %] # Foo Bar Baz |
58 | |
59 | =head2 remove(pattern) |
60 | |
61 | Outputs the string with all instances of the pattern (specified |
62 | as a Perl regular expression) removed. |
63 | |
64 | [% name = 'foo, bar & baz' %] |
65 | [% name.remove('\W+') %] # foobarbaz |
66 | |
67 | =head2 match(pattern, global) |
68 | |
69 | Performs a regular expression match on the string using the pattern |
70 | passed as an argument. If the pattern matches the string then the |
71 | method returns a reference to a list of any strings captured within |
72 | parenthesis in the pattern. |
73 | |
74 | [% name = 'Larry Wall' %] |
75 | [% matches = name.match('(\w+) (\w+)') %] |
76 | [% matches.1 %], [% matches.0 %] # Wall, Larry |
77 | |
78 | If the pattern does not match then the method returns false, rather |
79 | than returning an empty list which Perl and the Template Toolkit both |
80 | consider to be a true value. This allows you to write expression like |
81 | this. |
82 | |
83 | [% "We're not worthy!" IF name.match('Larry Wall') %] |
84 | |
85 | [% IF (matches = name.match('(\w+) (\w+)')) %] |
86 | pattern matches: [% matches.join(', ') %] |
87 | [% ELSE %] |
88 | pattern does not match |
89 | [% END %] |
90 | |
91 | Any regex modifiers, like C</s>, should be added in the regex using |
92 | the C<(?s)> syntax. For example, to modify the regex to disregard |
93 | whitespace (the C</x> switch), use: |
94 | |
95 | [% re = '(?x) |
96 | (\w+) |
97 | [ ] |
98 | (\w+) |
99 | '; |
100 | matches = name.match(re); |
101 | %] |
102 | |
103 | To perform a global search to match the pattern as many times as it |
104 | appears in the source string, provide a true value for the C<global> |
105 | argument following the pattern. |
106 | |
107 | [% text = 'bandanna'; |
108 | text.match('an+', 1).join(', ) # an, ann |
109 | %] |
110 | |
111 | =head2 search(pattern) |
112 | |
113 | Performs a similar function to L<match> but simply returns true if the |
114 | string matches the regular expression pattern passed as an argument. |
115 | |
116 | [% name = 'foo bar baz' %] |
117 | [% name.search('bar') ? 'bar' : 'no bar' %] # bar |
118 | |
119 | This virtual method is now deprecated in favour of L<match>. Move along |
120 | now, there's nothing more to see here. |
121 | |
122 | =head2 split(pattern) |
123 | |
124 | Calls Perl's C<split()> function to split a string into a list of |
125 | strings. |
126 | |
127 | [% FOREACH dir IN mypath.split(':') %] |
128 | [% dir %] |
129 | [% END %] |
130 | |
131 | =head2 chunk(size) |
132 | |
133 | Splits the value into a list of chunks of a certain size. |
134 | |
135 | [% ccard_no = "1234567824683579"; |
136 | ccard_no.chunk(4).join |
137 | %] |
138 | |
139 | Output: |
140 | |
141 | 1234 5678 2468 3579 |
142 | |
143 | If the size is specified as a negative number then the text will |
144 | be chunked from right-to-left. This gives the correct grouping |
145 | for numbers, for example. |
146 | |
147 | [% number = 1234567; |
148 | number.chunk(-3).join(',') |
149 | %] |
150 | |
151 | Output: |
152 | |
153 | 1,234,567 |
154 | |
155 | =head2 substr(offset, length, replacement) |
156 | |
157 | Returns a substring starting at C<offset>, for C<length> characters. |
158 | |
159 | [% str 'foo bar baz wiz waz woz') %] |
160 | [% str.substr(4, 3) %] # bar |
161 | |
162 | If C<length> is not specified then it returns everything from the |
163 | C<offset> to the end of the string. |
164 | |
165 | [% str.substr(12) %] # wiz waz woz |
166 | |
167 | If both C<length> and C<replacement> are specified, then the method |
168 | replaces everything from C<offset> for C<length> characters with |
169 | C<$replacement>. The substring removed from the string is then returned. |
170 | |
171 | [% str.substr(0, 11, 'FOO') %] # foo bar baz |
172 | [% str %] # FOO wiz waz woz |
173 | |
174 | =head2 list |
175 | |
176 | Return the value as a single element list. This can be useful if you |
177 | have a variable which may contain a single item or a list and you want |
178 | to treat them equally. The C<list> method can be called against a list |
179 | reference and will simply return the original reference, effectively |
180 | a no-op. |
181 | |
182 | [% thing.list.size %] # thing can be a scalar or a list |
183 | |
184 | =head2 hash |
185 | |
186 | Return the value as a hash reference containing a single entry with |
187 | the key C<value> indicating the original scalar value. As with the |
188 | C<list> virtual method, this is generally used to help massage data |
189 | into different formats. |
190 | |
191 | =head2 size |
192 | |
193 | Always returns 1 for scalar values. This method is provided for |
194 | consistency with the hash and list size methods. |
195 | |
196 | =head1 Hash Virtual Methods |
197 | |
198 | =head2 keys |
199 | |
200 | Returns a list of keys in the hash. They are not returned in any |
201 | particular order, but the order is the same as for the corresponding |
202 | values method. |
203 | |
204 | [% FOREACH key IN hash.keys %] |
205 | * [% key %] |
206 | [% END %] |
207 | |
208 | If you want the keys in sorted order, use the list C<sort> method. |
209 | |
210 | [% FOREACH key IN hash.keys.sort %] |
211 | * [% key %] |
212 | [% END %] |
213 | |
214 | Having got the keys in sorted order, you can then use variable |
215 | interpolation to fetch the value. This is shown in the following |
216 | example by the use of C<$key> to fetch the item from C<hash> whose |
217 | key is stored in the C<key> variable. |
218 | |
219 | [% FOREACH key IN hash.keys.sort %] |
220 | * [% key %] = [% hash.$key %] |
221 | [% END %] |
222 | |
223 | Alternately, you can use the C<pairs> method to get a list of |
224 | key/value pairs in sorted order. |
225 | |
226 | =head2 values |
227 | |
228 | Returns a list of the values in the hash. As with the C<keys> method, |
229 | they are not returned in any particular order, although it is the same |
230 | order that the keys are returned in. |
231 | |
232 | [% hash.values.join(', ') %] |
233 | |
234 | =head2 items |
235 | |
236 | Returns a list of both the keys and the values expanded into a single list. |
237 | |
238 | [% hash = { |
239 | a = 10 |
240 | b = 20 |
241 | }; |
242 | |
243 | hash.items.join(', ') # a, 10, b, 20 |
244 | %] |
245 | |
246 | =head2 each |
247 | |
248 | This method currently returns the same thing as the C<items> method. |
249 | |
250 | However, please note that this method will change in the next major |
251 | version of the Template Toolkit (v3) to return the same thing as the |
252 | C<pairs> method. This will be done in an effort to make these virtual |
253 | method more consistent with each other and how Perl works. |
254 | |
255 | In anticipation of this, we recommend that you stop using C<hash.each> |
256 | and instead use C<hash.items>. |
257 | |
258 | =head2 pairs |
259 | |
260 | This method returns a list of key/value pairs. They are returned in |
261 | sorted order according to the keys. |
262 | |
263 | [% FOREACH pair IN product.pairs %] |
264 | * [% pair.key %] is [% pair.value %] |
265 | [% END %] |
266 | |
267 | =head2 list |
268 | |
269 | Returns the contents of the hash in list form. An argument can be |
270 | passed to indicate the desired items required in the list: C<keys> to |
271 | return a list of the keys (same as C<hash.keys>), C<values> to return a |
272 | list of the values (same as C<hash.values>), C<each> to return as list |
273 | of key and values (same as C<hash.each>), or C<pairs> to return a list |
274 | of key/value pairs (same as C<hash.pairs>). |
275 | |
276 | [% keys = hash.list('keys') %] |
277 | [% values = hash.list('values') %] |
278 | [% items = hash.list('each') %] |
279 | [% pairs = hash.list('pairs') %] |
280 | |
281 | When called without an argument it currently returns the same thing as |
282 | the C<pairs> method. However, please note that this method will change |
283 | in the next major version of the Template Toolkit (v3) to return a |
284 | reference to a list containing the single hash reference (as per the |
285 | scalar list method). |
286 | |
287 | In anticipation of this, we recommend that you stop using C<hash.list> |
288 | and instead use C<hash.pairs>. |
289 | |
290 | =head2 sort, nsort |
291 | |
292 | Return a list of the keys, sorted alphabetically (C<sort>) or numerically |
293 | (C<nsort>) according to the corresponding values in the hash. |
294 | |
295 | [% FOREACH n IN phones.sort %] |
296 | [% phones.$n %] is [% n %], |
297 | [% END %] |
298 | |
299 | =head2 import |
300 | |
301 | The C<import> method can be called on a hash array to import the contents |
302 | of another hash array. |
303 | |
304 | [% hash1 = { |
305 | foo = 'Foo' |
306 | bar = 'Bar' |
307 | } |
308 | hash2 = { |
309 | wiz = 'Wiz' |
310 | woz = 'Woz' |
311 | } |
312 | %] |
313 | |
314 | [% hash1.import(hash2) %] |
315 | [% hash1.wiz %] # Wiz |
316 | |
317 | You can also call the C<import()> method by itself to import a hash array |
318 | into the current namespace hash. |
319 | |
320 | [% user = { id => 'lwall', name => 'Larry Wall' } %] |
321 | [% import(user) %] |
322 | [% id %]: [% name %] # lwall: Larry Wall |
323 | |
324 | =head2 defined, exists |
325 | |
326 | Returns a true or false value if an item in the hash denoted by the key |
327 | passed as an argument is defined or exists, respectively. |
328 | |
329 | [% hash.defined('somekey') ? 'yes' : 'no' %] |
330 | [% hash.exists('somekey') ? 'yes' : 'no' %] |
331 | |
332 | When called without any argument, C<hash.defined> returns true if the hash |
333 | itself is defined (e.g. the same effect as C<scalar.defined>). |
334 | |
335 | =head2 delete |
336 | |
337 | Delete one or more items from the hash. |
338 | |
339 | [% hash.delete('foo', 'bar') %] |
340 | |
341 | =head2 size |
342 | |
343 | Returns the number of key/value pairs in the hash. |
344 | |
345 | =head2 item |
346 | |
347 | Returns an item from the hash using a key passed as an argument. |
348 | |
349 | [% hash.item('foo') %] # same as hash.foo |
350 | |
351 | =head1 List Virtual Methods |
352 | |
353 | =head2 first, last |
354 | |
355 | Returns the first/last item in the list. The item is not removed from the |
356 | list. |
357 | |
358 | [% results.first %] to [% results.last %] |
359 | |
360 | If either is given a numeric argument C<n>, they return the first or |
361 | last C<n> elements: |
362 | |
363 | The first 5 results are [% results.first(5).join(", ") %]. |
364 | |
365 | =head2 size, max |
366 | |
367 | Returns the size of a list (number of elements) and the maximum |
368 | index number (size - 1), respectively. |
369 | |
370 | [% results.size %] search results matched your query |
371 | |
372 | =head2 defined |
373 | |
374 | Returns a true or false value if the item in the list denoted by the |
375 | argument is defined. |
376 | |
377 | [% list.defined(3) ? 'yes' : 'no' %] |
378 | |
379 | When called without any argument, C<list.defined> returns true if the list |
380 | itself is defined (e.g. the same effect as C<scalar.defined>). |
381 | |
382 | =head2 reverse |
383 | |
384 | Returns the items of the list in reverse order. |
385 | |
386 | [% FOREACH s IN scores.reverse %] |
387 | ... |
388 | [% END %] |
389 | |
390 | =head2 join |
391 | |
392 | Joins the items in the list into a single string, using Perl's C<join()> |
393 | function. |
394 | |
395 | [% items.join(', ') %] |
396 | |
397 | =head2 grep |
398 | |
399 | Returns a list of the items in the list that match a regular expression |
400 | pattern. |
401 | |
402 | [% FOREACH directory.files.grep('\.txt$') %] |
403 | ... |
404 | [% END %] |
405 | |
406 | =head2 sort, nsort |
407 | |
408 | Returns the items in alpha (C<sort>) or numerical (C<nsort>) order. |
409 | |
410 | [% library = books.sort %] |
411 | |
412 | An argument can be provided to specify a search key. Where an item in |
413 | the list is a hash reference, the search key will be used to retrieve a |
414 | value from the hash which will then be used as the comparison value. |
415 | Where an item is an object which implements a method of that name, the |
416 | method will be called to return a comparison value. |
417 | |
418 | [% library = books.sort('author') %] |
419 | |
420 | In the example, the C<books> list can contains hash references with |
421 | an C<author> key or objects with an C<author> method. |
422 | |
423 | You can also specify multiple sort keys. |
424 | |
425 | [% library = books.sort('author', 'title') %] |
426 | |
427 | In this case the books will be sorted primarily by author. If two or more |
428 | books have authors with the same name then they will be sorted by title. |
429 | |
430 | =head2 unshift(item), push(item) |
431 | |
432 | The C<push()> method adds an item or items to the end of list. |
433 | |
434 | [% mylist.push(foo) %] |
435 | [% mylist.push(foo, bar) %] |
436 | |
437 | The C<unshift()> method adds an item or items to the start of a list. |
438 | |
439 | [% mylist.unshift(foo) %] |
440 | [% mylist.push(foo, bar) %] |
441 | |
442 | =head2 shift, pop |
443 | |
444 | Removes the first/last item from the list and returns it. |
445 | |
446 | [% first = mylist.shift %] |
447 | [% last = mylist.pop %] |
448 | |
449 | =head2 unique |
450 | |
451 | Returns a list of the unique elements in a list, in the same order |
452 | as in the list itself. |
453 | |
454 | [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %] |
455 | [% numbers = mylist.unique %] |
456 | |
457 | While this can be explicitly sorted, it is not required that the list |
458 | be sorted before the unique elements are pulled out (unlike the Unix |
459 | command line utility). |
460 | |
461 | [% numbers = mylist.unique.sort %] |
462 | |
463 | =head2 import |
464 | |
465 | Appends the contents of one or more other lists to the end of the |
466 | current list. |
467 | |
468 | [% one = [ 1 2 3 ]; |
469 | two = [ 4 5 6 ]; |
470 | three = [ 7 8 9 ]; |
471 | one.import(two, three); |
472 | one.join(', ); # 1, 2, 3, 4, 5, 6, 7, 8, 9 |
473 | %] |
474 | |
475 | =head2 merge |
476 | |
477 | Returns a list composed of zero or more other lists: |
478 | |
479 | [% list_one = [ 1 2 3 ]; |
480 | list_two = [ 4 5 6 ]; |
481 | list_three = [ 7 8 9 ]; |
482 | list_four = list_one.merge(list_two, list_three); |
483 | %] |
484 | |
485 | The original lists are not modified. |
486 | |
487 | =head2 slice(from, to) |
488 | |
489 | Returns a slice of items in the list between the bounds passed as |
490 | arguments. If the second argument, C<to>, isn't specified, then it |
491 | defaults to the last item in the list. The original list is not |
492 | modified. |
493 | |
494 | [% first_three = list.slice(0,2) %] |
495 | [% last_three = list.slice(-3, -1) %] |
496 | |
497 | =head2 splice(offset, length, list) |
498 | |
499 | Behaves just like Perl's C<splice()> function allowing you to selectively |
500 | remove and/or replace elements in a list. It removes C<length> items |
501 | from the list, starting at C<offset> and replaces them with the items |
502 | in C<list>. |
503 | |
504 | [% play_game = [ 'play', 'scrabble' ]; |
505 | ping_pong = [ 'ping', 'pong' ]; |
506 | redundant = play_game.splice(1, 1, ping_pong); |
507 | redundant.join; # scrabble |
508 | play_game.join; # play ping pong |
509 | %] |
510 | |
511 | The method returns a list of the items removed by the splice. |
512 | You can use the C<CALL> directive to ignore the output if you're |
513 | not planning to do anything with it. |
514 | |
515 | [% CALL play_game.splice(1, 1, ping_pong) %] |
516 | |
517 | As well as providing a reference to a list of replacement values, |
518 | you can pass in a list of items. |
519 | |
520 | [% CALL list.splice(-1, 0, 'foo', 'bar') %] |
521 | |
522 | Be careful about passing just one item in as a replacement value. |
523 | If it is a reference to a list then the contents of the list will |
524 | be used. If it's not a list, then it will be treated as a single |
525 | value. You can use square brackets around a single item if you |
526 | need to be explicit: |
527 | |
528 | [% # push a single item, an_item |
529 | CALL list.splice(-1, 0, an_item); |
530 | |
531 | # push the items from another_list |
532 | CALL list.splice(-1, 0, another_list); |
533 | |
534 | # push a reference to another_list |
535 | CALL list.splice(-1, 0, [ another_list ]); |
536 | %] |
537 | |
538 | =head2 hash |
539 | |
540 | Returns a reference to a hash array comprised of the elements in the |
541 | list. The even-numbered elements (0, 2, 4, etc) become the keys and |
542 | the odd-numbered elements (1, 3, 5, etc) the values. |
543 | |
544 | [% list = ['pi', 3.14, 'e', 2.718] %] |
545 | [% hash = list.hash %] |
546 | [% hash.pi %] # 3.14 |
547 | [% hash.e %] # 2.718 |
548 | |
549 | If a numerical argument is provided then the hash returned will have |
550 | keys generated for each item starting at the number specified. |
551 | |
552 | [% list = ['beer', 'peanuts'] %] |
553 | [% hash = list.hash(1) %] |
554 | [% hash.1 %] # beer |
555 | [% hash.2 %] # peanuts |
556 | |
557 | =head1 Automagic Promotion of Scalar to List for Virtual Methods |
558 | |
559 | In addition to the scalar virtual methods listed in the previous |
560 | section, you can also call any list virtual method against a scalar. |
561 | The item will be automagically promoted to a single element list and |
562 | the appropriate list virtual method will be called. |
563 | |
564 | One particular benefit of this comes when calling subroutines or |
565 | object methods that return a list of items, rather than the |
566 | preferred reference to a list of items. In this case, the |
567 | Template Toolkit automatically folds the items returned into |
568 | a list. |
569 | |
570 | The upshot is that you can continue to use existing Perl modules or |
571 | code that returns lists of items, without having to refactor it |
572 | just to keep the Template Toolkit happy (by returning references |
573 | to list). C<Class::DBI> module is just one example of a particularly |
574 | useful module which returns values this way. |
575 | |
576 | If only a single item is returned from a subroutine then the |
577 | Template Toolkit assumes it meant to return a single item (rather |
578 | than a list of 1 item) and leaves it well alone, returning the |
579 | single value as it is. If you're executing a database query, |
580 | for example, you might get 1 item returned, or perhaps many |
581 | items which are then folded into a list. |
582 | |
583 | The C<FOREACH> directive will happily accept either a list or a single item |
584 | which it will treat as a list. So it's safe to write directives like this, |
585 | where we assume that the C<something> variable is bound to a subroutine which |
586 | may return one or more items: |
587 | |
588 | [% FOREACH item IN something %] |
589 | ... |
590 | [% END %] |
591 | |
592 | The automagic promotion of scalars to single item lists means |
593 | that you can also use list virtual methods safely, even if you |
594 | only get one item returned. For example: |
595 | |
596 | [% something.first %] |
597 | [% something.join %] |
598 | [% something.reverse.join(', ') %] |
599 | |
600 | Note that this is very much a last-ditch behaviour. If the single |
601 | item return is an object with a C<first> method, for example, then that |
602 | will be called, as expected, in preference to the list virtual method. |
603 | |
604 | =head1 Defining Custom Virtual Methods |
605 | |
606 | You can define your own virtual methods for scalars, lists and hash arrays. |
607 | The L<Template::Stash> package variables C<$SCALAR_OPS>, C<$LIST_OPS> and |
608 | C<$HASH_OPS> are references to hash arrays that define these virtual methods. |
609 | C<HASH_OPS> and C<LIST_OPS> methods are subroutines that accept a hash/list |
610 | reference as the first item. C<SCALAR_OPS> are subroutines that accept a scalar |
611 | value as the first item. Any other arguments specified when the method is |
612 | called will be passed to the subroutine. |
613 | |
614 | # load Template::Stash to make method tables visible |
615 | use Template::Stash; |
616 | |
617 | # define list method to return new list of odd numbers only |
618 | $Template::Stash::LIST_OPS->{ odd } = sub { |
619 | my $list = shift; |
620 | return [ grep { $_ % 2 } @$list ]; |
621 | }; |
622 | |
623 | Example template: |
624 | |
625 | [% primes = [ 2, 3, 5, 7, 9 ] %] |
626 | [% primes.odd.join(', ') %] # 3, 5, 7, 9 |
627 | |
628 | TODO: document the define_vmethod() method which makes this even easier |
629 | |
630 | =cut |
631 | |
632 | # Local Variables: |
633 | # mode: perl |
634 | # perl-indent-level: 4 |
635 | # indent-tabs-mode: nil |
636 | # End: |
637 | # |
638 | # vim: expandtab shiftwidth=4: |