1 #============================================================= -*-perl-*-
3 # Template::Manual::VMethods
6 # Andy Wardley <abw@wardley.org>
9 # Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
11 # This module is free software; you can redistribute it and/or
12 # modify it under the same terms as Perl itself.
14 #========================================================================
18 Template::Manual::VMethods - Virtual Methods
20 =head1 Scalar Virtual Methods
24 Returns true if the value is defined.
26 [% user = get_user(uid) IF uid.defined %]
30 Returns the length of the string representation of the item:
32 [% IF password.length < 8 %]
33 Password too short, dumbass!
38 Repeat the string a specified number of times.
41 [% name.repeat(3) %] # foofoofoo
43 =head2 replace(search, replace)
45 Outputs the string with all instances of the first argument (specified
46 as a Perl regular expression) with the second.
48 [% name = 'foo, bar & baz' %]
49 [% name.replace('\W+', '_') %] # foo_bar_baz
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.
56 [% name = 'FooBarBaz' %]
57 [% name.replace('([A-Z])', ' $1') %] # Foo Bar Baz
59 =head2 remove(pattern)
61 Outputs the string with all instances of the pattern (specified
62 as a Perl regular expression) removed.
64 [% name = 'foo, bar & baz' %]
65 [% name.remove('\W+') %] # foobarbaz
67 =head2 match(pattern, global)
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.
74 [% name = 'Larry Wall' %]
75 [% matches = name.match('(\w+) (\w+)') %]
76 [% matches.1 %], [% matches.0 %] # Wall, Larry
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
83 [% "We're not worthy!" IF name.match('Larry Wall') %]
85 [% IF (matches = name.match('(\w+) (\w+)')) %]
86 pattern matches: [% matches.join(', ') %]
88 pattern does not match
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:
100 matches = name.match(re);
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.
107 [% text = 'bandanna';
108 text.match('an+', 1).join(', ) # an, ann
111 =head2 search(pattern)
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.
116 [% name = 'foo bar baz' %]
117 [% name.search('bar') ? 'bar' : 'no bar' %] # bar
119 This virtual method is now deprecated in favour of L<match>. Move along
120 now, there's nothing more to see here.
122 =head2 split(pattern)
124 Calls Perl's C<split()> function to split a string into a list of
127 [% FOREACH dir IN mypath.split(':') %]
133 Splits the value into a list of chunks of a certain size.
135 [% ccard_no = "1234567824683579";
136 ccard_no.chunk(4).join
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.
148 number.chunk(-3).join(',')
155 =head2 substr(offset, length, replacement)
157 Returns a substring starting at C<offset>, for C<length> characters.
159 [% str 'foo bar baz wiz waz woz') %]
160 [% str.substr(4, 3) %] # bar
162 If C<length> is not specified then it returns everything from the
163 C<offset> to the end of the string.
165 [% str.substr(12) %] # wiz waz woz
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.
171 [% str.substr(0, 11, 'FOO') %] # foo bar baz
172 [% str %] # FOO wiz waz woz
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
182 [% thing.list.size %] # thing can be a scalar or a list
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.
193 Always returns 1 for scalar values. This method is provided for
194 consistency with the hash and list size methods.
196 =head1 Hash Virtual Methods
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
204 [% FOREACH key IN hash.keys %]
208 If you want the keys in sorted order, use the list C<sort> method.
210 [% FOREACH key IN hash.keys.sort %]
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.
219 [% FOREACH key IN hash.keys.sort %]
220 * [% key %] = [% hash.$key %]
223 Alternately, you can use the C<pairs> method to get a list of
224 key/value pairs in sorted order.
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.
232 [% hash.values.join(', ') %]
236 Returns a list of both the keys and the values expanded into a single list.
243 hash.items.join(', ') # a, 10, b, 20
248 This method currently returns the same thing as the C<items> method.
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.
255 In anticipation of this, we recommend that you stop using C<hash.each>
256 and instead use C<hash.items>.
260 This method returns a list of key/value pairs. They are returned in
261 sorted order according to the keys.
263 [% FOREACH pair IN product.pairs %]
264 * [% pair.key %] is [% pair.value %]
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>).
276 [% keys = hash.list('keys') %]
277 [% values = hash.list('values') %]
278 [% items = hash.list('each') %]
279 [% pairs = hash.list('pairs') %]
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
287 In anticipation of this, we recommend that you stop using C<hash.list>
288 and instead use C<hash.pairs>.
292 Return a list of the keys, sorted alphabetically (C<sort>) or numerically
293 (C<nsort>) according to the corresponding values in the hash.
295 [% FOREACH n IN phones.sort %]
296 [% phones.$n %] is [% n %],
301 The C<import> method can be called on a hash array to import the contents
302 of another hash array.
314 [% hash1.import(hash2) %]
315 [% hash1.wiz %] # Wiz
317 You can also call the C<import()> method by itself to import a hash array
318 into the current namespace hash.
320 [% user = { id => 'lwall', name => 'Larry Wall' } %]
322 [% id %]: [% name %] # lwall: Larry Wall
324 =head2 defined, exists
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.
329 [% hash.defined('somekey') ? 'yes' : 'no' %]
330 [% hash.exists('somekey') ? 'yes' : 'no' %]
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>).
337 Delete one or more items from the hash.
339 [% hash.delete('foo', 'bar') %]
343 Returns the number of key/value pairs in the hash.
347 Returns an item from the hash using a key passed as an argument.
349 [% hash.item('foo') %] # same as hash.foo
351 =head1 List Virtual Methods
355 Returns the first/last item in the list. The item is not removed from the
358 [% results.first %] to [% results.last %]
360 If either is given a numeric argument C<n>, they return the first or
363 The first 5 results are [% results.first(5).join(", ") %].
367 Returns the size of a list (number of elements) and the maximum
368 index number (size - 1), respectively.
370 [% results.size %] search results matched your query
374 Returns a true or false value if the item in the list denoted by the
377 [% list.defined(3) ? 'yes' : 'no' %]
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>).
384 Returns the items of the list in reverse order.
386 [% FOREACH s IN scores.reverse %]
392 Joins the items in the list into a single string, using Perl's C<join()>
395 [% items.join(', ') %]
399 Returns a list of the items in the list that match a regular expression
402 [% FOREACH directory.files.grep('\.txt$') %]
408 Returns the items in alpha (C<sort>) or numerical (C<nsort>) order.
410 [% library = books.sort %]
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.
418 [% library = books.sort('author') %]
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.
423 You can also specify multiple sort keys.
425 [% library = books.sort('author', 'title') %]
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.
430 =head2 unshift(item), push(item)
432 The C<push()> method adds an item or items to the end of list.
434 [% mylist.push(foo) %]
435 [% mylist.push(foo, bar) %]
437 The C<unshift()> method adds an item or items to the start of a list.
439 [% mylist.unshift(foo) %]
440 [% mylist.push(foo, bar) %]
444 Removes the first/last item from the list and returns it.
446 [% first = mylist.shift %]
447 [% last = mylist.pop %]
451 Returns a list of the unique elements in a list, in the same order
452 as in the list itself.
454 [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
455 [% numbers = mylist.unique %]
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).
461 [% numbers = mylist.unique.sort %]
465 Appends the contents of one or more other lists to the end of the
471 one.import(two, three);
472 one.join(', ); # 1, 2, 3, 4, 5, 6, 7, 8, 9
477 Returns a list composed of zero or more other lists:
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);
485 The original lists are not modified.
487 =head2 slice(from, to)
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
494 [% first_three = list.slice(0,2) %]
495 [% last_three = list.slice(-3, -1) %]
497 =head2 splice(offset, length, list)
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
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
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.
515 [% CALL play_game.splice(1, 1, ping_pong) %]
517 As well as providing a reference to a list of replacement values,
518 you can pass in a list of items.
520 [% CALL list.splice(-1, 0, 'foo', 'bar') %]
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
528 [% # push a single item, an_item
529 CALL list.splice(-1, 0, an_item);
531 # push the items from another_list
532 CALL list.splice(-1, 0, another_list);
534 # push a reference to another_list
535 CALL list.splice(-1, 0, [ another_list ]);
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.
544 [% list = ['pi', 3.14, 'e', 2.718] %]
545 [% hash = list.hash %]
549 If a numerical argument is provided then the hash returned will have
550 keys generated for each item starting at the number specified.
552 [% list = ['beer', 'peanuts'] %]
553 [% hash = list.hash(1) %]
555 [% hash.2 %] # peanuts
557 =head1 Automagic Promotion of Scalar to List for Virtual Methods
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.
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
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.
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.
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:
588 [% FOREACH item IN something %]
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:
596 [% something.first %]
598 [% something.reverse.join(', ') %]
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.
604 =head1 Defining Custom Virtual Methods
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.
614 # load Template::Stash to make method tables visible
617 # define list method to return new list of odd numbers only
618 $Template::Stash::LIST_OPS->{ odd } = sub {
620 return [ grep { $_ % 2 } @$list ];
625 [% primes = [ 2, 3, 5, 7, 9 ] %]
626 [% primes.odd.join(', ') %] # 3, 5, 7, 9
628 TODO: document the define_vmethod() method which makes this even easier
634 # perl-indent-level: 4
635 # indent-tabs-mode: nil
638 # vim: expandtab shiftwidth=4: