1Template::Manual::VMethUosdesr(3C)ontributed Perl DocumeTnetmaptliaotne::Manual::VMethods(3)
2
3
4

NAME

6       Template::Manual::VMethods - Virtual Methods
7

Scalar Virtual Methods

9   defined
10       Returns true if the value is defined.
11
12           [% user = get_user(uid) IF uid.defined %]
13
14   length
15       Returns the length of the string representation of the item:
16
17           [% IF password.length < 8 %]
18              Password too short, dumbass!
19           [% END %]
20
21   repeat(n)
22       Repeat the string a specified number of times.
23
24           [% name = 'foo' %]
25           [% name.repeat(3) %]                # foofoofoo
26
27   replace(search, replace)
28       Outputs the string with all instances of the first argument (specified
29       as a Perl regular expression) with the second.
30
31           [% name = 'foo, bar & baz' %]
32           [% name.replace('\W+', '_') %]        # foo_bar_baz
33
34       You can use $1, $2, etc., to reference captured parts (in parentheses)
35       in the regular expression.  Just be careful to single quote the
36       replacement string.  If you use double quotes then TT will try and
37       interpolate the variables before passing the string to the "replace"
38       vmethod.
39
40           [% name = 'FooBarBaz' %]
41           [% name.replace('([A-Z])', ' $1') %]  # Foo Bar Baz
42
43   remove(pattern)
44       Outputs the string with all instances of the pattern (specified as a
45       Perl regular expression) removed.
46
47           [% name = 'foo, bar & baz' %]
48           [% name.remove('\W+') %]    # foobarbaz
49
50   match(pattern, global)
51       Performs a regular expression match on the string using the pattern
52       passed as an argument.  If the pattern matches the string then the
53       method returns a reference to a list of any strings captured within
54       parenthesis in the pattern.
55
56           [% name = 'Larry Wall' %]
57           [% matches = name.match('(\w+) (\w+)') %]
58           [% matches.1 %], [% matches.0 %]            # Wall, Larry
59
60       If the pattern does not match then the method returns false, rather
61       than returning an empty list which Perl and the Template Toolkit both
62       consider to be a true value.  This allows you to write expression like
63       this.
64
65           [% "We're not worthy!" IF name.match('Larry Wall') %]
66
67           [% IF (matches = name.match('(\w+) (\w+)')) %]
68              pattern matches: [% matches.join(', ') %]
69           [% ELSE %]
70              pattern does not match
71           [% END %]
72
73       Any regex modifiers, like "/s", should be added in the regex using the
74       "(?s)" syntax.  For example, to modify the regex to disregard
75       whitespace (the "/x" switch), use:
76
77           [% re = '(?x)
78                      (\w+)
79                      [ ]
80                      (\w+)
81                    ';
82             matches = name.match(re);
83           %]
84
85       To perform a global search to match the pattern as many times as it
86       appears in the source string, provide a true value for the "global"
87       argument following the pattern.
88
89           [% text = 'bandanna';
90              text.match('an+', 1).join(', )      # an, ann
91           %]
92
93   search(pattern)
94       Performs a similar function to match but simply returns true if the
95       string matches the regular expression pattern passed as an argument.
96
97           [% name = 'foo bar baz' %]
98           [% name.search('bar') ? 'bar' : 'no bar' %]     # bar
99
100       This virtual method is now deprecated in favour of match.  Move along
101       now, there's nothing more to see here.
102
103   split(pattern)
104       Calls Perl's "split()" function to split a string into a list of
105       strings.
106
107           [% FOREACH dir IN mypath.split(':') %]
108              [% dir %]
109           [% END %]
110
111   chunk(size)
112       Splits the value into a list of chunks of a certain size.
113
114           [% ccard_no = "1234567824683579";
115              ccard_no.chunk(4).join
116           %]
117
118       Output:
119
120           1234 5678 2468 3579
121
122       If the size is specified as a negative number then the text will be
123       chunked from right-to-left.  This gives the correct grouping for
124       numbers, for example.
125
126           [% number = 1234567;
127              number.chunk(-3).join(',')
128           %]
129
130       Output:
131
132           1,234,567
133
134   substr(offset, length, replacement)
135       Returns a substring starting at "offset", for "length" characters.
136
137           [% str 'foo bar baz wiz waz woz') %]
138           [% str.substr(4, 3) %]    # bar
139
140       If "length" is not specified then it returns everything from the
141       "offset" to the end of the string.
142
143           [% str.substr(12) %]      # wiz waz woz
144
145       If both "length" and "replacement" are specified, then the method
146       replaces everything from "offset" for "length" characters with
147       $replacement.  The substring removed from the string is then returned.
148
149           [% str.substr(0, 11, 'FOO') %]   # foo bar baz
150           [% str %]                        # FOO wiz waz woz
151
152   list
153       Return the value as a single element list.  This can be useful if you
154       have a variable which may contain a single item or a list and you want
155       to treat them equally.  The "list" method can be called against a list
156       reference and will simply return the original reference, effectively a
157       no-op.
158
159           [% thing.list.size %]  # thing can be a scalar or a list
160
161   hash
162       Return the value as a hash reference containing a single entry with the
163       key "value" indicating the original scalar value.  As with the "list"
164       virtual method, this is generally used to help massage data into
165       different formats.
166
167   size
168       Always returns 1 for scalar values.  This method is provided for
169       consistency with the hash and list size methods.
170

Hash Virtual Methods

172   keys
173       Returns a list of keys in the hash.  They are not returned in any
174       particular order, but the order is the same as for the corresponding
175       values method.
176
177           [% FOREACH key IN hash.keys %]
178              * [% key %]
179           [% END %]
180
181       If you want the keys in sorted order, use the list "sort" method.
182
183           [% FOREACH key IN hash.keys.sort %]
184              * [% key %]
185           [% END %]
186
187       Having got the keys in sorted order, you can then use variable
188       interpolation to fetch the value.  This is shown in the following
189       example by the use of $key to fetch the item from "hash" whose key is
190       stored in the "key" variable.
191
192           [% FOREACH key IN hash.keys.sort %]
193              * [% key %] = [% hash.$key %]
194           [% END %]
195
196       Alternately, you can use the "pairs" method to get a list of key/value
197       pairs in sorted order.
198
199   values
200       Returns a list of the values in the hash.  As with the "keys" method,
201       they are not returned in any particular order, although it is the same
202       order that the keys are returned in.
203
204           [% hash.values.join(', ') %]
205
206   items
207       Returns a list of both the keys and the values expanded into a single
208       list.
209
210           [% hash = {
211                 a = 10
212                 b = 20
213              };
214
215              hash.items.join(', ')    # a, 10, b, 20
216           %]
217
218   each
219       This method currently returns the same thing as the "items" method.
220
221       However, please note that this method will change in the next major
222       version of the Template Toolkit (v3) to return the same thing as the
223       "pairs" method.  This will be done in an effort to make these virtual
224       method more consistent with each other and how Perl works.
225
226       In anticipation of this, we recommend that you stop using "hash.each"
227       and instead use "hash.items".
228
229   pairs
230       This method returns a list of key/value pairs.  They are returned in
231       sorted order according to the keys.
232
233           [% FOREACH pair IN product.pairs %]
234              * [% pair.key %] is [% pair.value %]
235           [% END %]
236
237   list
238       Returns the contents of the hash in list form.  An argument can be
239       passed to indicate the desired items required in the list: "keys" to
240       return a list of the keys (same as "hash.keys"), "values" to return a
241       list of the values (same as "hash.values"), "each" to return as list of
242       key and values (same as "hash.each"), or "pairs" to return a list of
243       key/value pairs (same as "hash.pairs").
244
245           [% keys   = hash.list('keys') %]
246           [% values = hash.list('values') %]
247           [% items  = hash.list('each') %]
248           [% pairs  = hash.list('pairs') %]
249
250       When called without an argument it currently returns the same thing as
251       the "pairs" method.  However, please note that this method will change
252       in the next major version of the Template Toolkit (v3) to return a
253       reference to a list containing the single hash reference (as per the
254       scalar list method).
255
256       In anticipation of this, we recommend that you stop using "hash.list"
257       and instead use "hash.pairs".
258
259   sort, nsort
260       Return a list of the keys, sorted alphabetically ("sort") or
261       numerically ("nsort") according to the corresponding values in the
262       hash.
263
264           [% FOREACH n IN phones.sort %]
265              [% phones.$n %] is [% n %],
266           [% END %]
267
268   import
269       The "import" method can be called on a hash array to import the
270       contents of another hash array.
271
272           [% hash1 = {
273                foo = 'Foo'
274                bar = 'Bar'
275              }
276              hash2 = {
277                  wiz = 'Wiz'
278                  woz = 'Woz'
279              }
280           %]
281
282           [% hash1.import(hash2) %]
283           [% hash1.wiz %]             # Wiz
284
285       You can also call the "import()" method by itself to import a hash
286       array into the current namespace hash.
287
288           [% user = { id => 'lwall', name => 'Larry Wall' } %]
289           [% import(user) %]
290           [% id %]: [% name %]        # lwall: Larry Wall
291
292   defined, exists
293       Returns a true or false value if an item in the hash denoted by the key
294       passed as an argument is defined or exists, respectively.
295
296           [% hash.defined('somekey') ? 'yes' : 'no' %]
297           [% hash.exists('somekey') ? 'yes' : 'no' %]
298
299       When called without any argument, "hash.defined" returns true if the
300       hash itself is defined (e.g. the same effect as "scalar.defined").
301
302   delete
303       Delete one or more items from the hash.
304
305           [% hash.delete('foo', 'bar') %]
306
307   size
308       Returns the number of key/value pairs in the hash.
309
310   item
311       Returns an item from the hash using a key passed as an argument.
312
313           [% hash.item('foo') %]  # same as hash.foo
314

List Virtual Methods

316   first, last
317       Returns the first/last item in the list.  The item is not removed from
318       the list.
319
320           [% results.first %] to [% results.last %]
321
322       If either is given a numeric argument "n", they return the first or
323       last "n" elements:
324
325           The first 5 results are [% results.first(5).join(", ") %].
326
327   size, max
328       Returns the size of a list (number of elements) and the maximum index
329       number (size - 1), respectively.
330
331           [% results.size %] search results matched your query
332
333   defined
334       Returns a true or false value if the item in the list denoted by the
335       argument is defined.
336
337           [% list.defined(3) ? 'yes' : 'no' %]
338
339       When called without any argument, "list.defined" returns true if the
340       list itself is defined (e.g. the same effect as "scalar.defined").
341
342   reverse
343       Returns the items of the list in reverse order.
344
345           [% FOREACH s IN scores.reverse %]
346              ...
347           [% END %]
348
349   join
350       Joins the items in the list into a single string, using Perl's "join()"
351       function.
352
353           [% items.join(', ') %]
354
355   grep
356       Returns a list of the items in the list that match a regular expression
357       pattern.
358
359           [% FOREACH directory.files.grep('\.txt$') %]
360              ...
361           [% END %]
362
363   sort, nsort
364       Returns the items in alpha ("sort") or numerical ("nsort") order.
365
366           [% library = books.sort %]
367
368       An argument can be provided to specify a search key.  Where an item in
369       the list is a hash reference, the search key will be used to retrieve a
370       value from the hash which will then be used as the comparison value.
371       Where an item is an object which implements a method of that name, the
372       method will be called to return a comparison value.
373
374           [% library = books.sort('author') %]
375
376       In the example, the "books" list can contains hash references with an
377       "author" key or objects with an "author" method.
378
379       You can also specify multiple sort keys.
380
381           [% library = books.sort('author', 'title') %]
382
383       In this case the books will be sorted primarily by author.  If two or
384       more books have authors with the same name then they will be sorted by
385       title.
386
387   unshift(item), push(item)
388       The "push()" method adds an item or items to the end of list.
389
390           [% mylist.push(foo) %]
391           [% mylist.push(foo, bar) %]
392
393       The "unshift()" method adds an item or items to the start of a list.
394
395           [% mylist.unshift(foo) %]
396           [% mylist.push(foo, bar)    %]
397
398   shift, pop
399       Removes the first/last item from the list and returns it.
400
401           [% first = mylist.shift %]
402           [% last  = mylist.pop   %]
403
404   unique
405       Returns a list of the unique elements in a list, in the same order as
406       in the list itself.
407
408           [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
409           [% numbers = mylist.unique %]
410
411       While this can be explicitly sorted, it is not required that the list
412       be sorted before the unique elements are pulled out (unlike the Unix
413       command line utility).
414
415           [% numbers = mylist.unique.sort %]
416
417   import
418       Appends the contents of one or more other lists to the end of the
419       current list.
420
421           [% one   = [ 1 2 3 ];
422              two   = [ 4 5 6 ];
423              three = [ 7 8 9 ];
424              one.import(two, three);
425              one.join(', );     # 1, 2, 3, 4, 5, 6, 7, 8, 9
426           %]
427
428   merge
429       Returns a list composed of zero or more other lists:
430
431           [% list_one = [ 1 2 3 ];
432              list_two = [ 4 5 6 ];
433              list_three = [ 7 8 9 ];
434              list_four = list_one.merge(list_two, list_three);
435           %]
436
437       The original lists are not modified.
438
439   slice(from, to)
440       Returns a slice of items in the list between the bounds passed as
441       arguments.  If the second argument, "to", isn't specified, then it
442       defaults to the last item in the list.  The original list is not
443       modified.
444
445           [% first_three = list.slice(0,2) %]
446           [% last_three  = list.slice(-3, -1) %]
447
448   splice(offset, length, list)
449       Behaves just like Perl's "splice()" function allowing you to
450       selectively remove and/or replace elements in a list.  It removes
451       "length" items from the list, starting at "offset" and replaces them
452       with the items in "list".
453
454           [% play_game = [ 'play', 'scrabble' ];
455              ping_pong = [ 'ping', 'pong' ];
456              redundant = play_game.splice(1, 1, ping_pong);
457              redundant.join;     # scrabble
458              play_game.join;     # play ping pong
459           %]
460
461       The method returns a list of the items removed by the splice.  You can
462       use the "CALL" directive to ignore the output if you're not planning to
463       do anything with it.
464
465           [% CALL play_game.splice(1, 1, ping_pong) %]
466
467       As well as providing a reference to a list of replacement values, you
468       can pass in a list of items.
469
470           [% CALL list.splice(-1, 0, 'foo', 'bar') %]
471
472       Be careful about passing just one item in as a replacement value.  If
473       it is a reference to a list then the contents of the list will be used.
474       If it's not a list, then it will be treated as a single value.  You can
475       use square brackets around a single item if you need to be explicit:
476
477           [% # push a single item, an_item
478              CALL list.splice(-1, 0, an_item);
479
480              # push the items from another_list
481              CALL list.splice(-1, 0, another_list);
482
483              # push a reference to another_list
484              CALL list.splice(-1, 0, [ another_list ]);
485           %]
486
487   hash
488       Returns a reference to a hash array comprised of the elements in the
489       list.  The even-numbered elements (0, 2, 4, etc) become the keys and
490       the odd-numbered elements (1, 3, 5, etc) the values.
491
492           [% list = ['pi', 3.14, 'e', 2.718] %]
493           [% hash = list.hash %]
494           [% hash.pi %]               # 3.14
495           [% hash.e  %]               # 2.718
496
497       If a numerical argument is provided then the hash returned will have
498       keys generated for each item starting at the number specified.
499
500           [% list = ['beer', 'peanuts'] %]
501           [% hash = list.hash(1) %]
502           [% hash.1  %]               # beer
503           [% hash.2  %]               # peanuts
504

Automagic Promotion of Scalar to List for Virtual Methods

506       In addition to the scalar virtual methods listed in the previous
507       section, you can also call any list virtual method against a scalar.
508       The item will be automagically promoted to a single element list and
509       the appropriate list virtual method will be called.
510
511       One particular benefit of this comes when calling subroutines or object
512       methods that return a list of items, rather than the preferred
513       reference to a list of items.  In this case, the Template Toolkit
514       automatically folds the items returned into a list.
515
516       The upshot is that you can continue to use existing Perl modules or
517       code that returns lists of items, without having to refactor it just to
518       keep the Template Toolkit happy (by returning references to list).
519       "Class::DBI" module is just one example of a particularly useful module
520       which returns values this way.
521
522       If only a single item is returned from a subroutine then the Template
523       Toolkit assumes it meant to return a single item (rather than a list of
524       1 item) and leaves it well alone, returning the single value as it is.
525       If you're executing a database query, for example, you might get 1 item
526       returned, or perhaps many items which are then folded into a list.
527
528       The "FOREACH" directive will happily accept either a list or a single
529       item which it will treat as a list. So it's safe to write directives
530       like this, where we assume that the "something" variable is bound to a
531       subroutine which may return one or more items:
532
533           [% FOREACH item IN something %]
534              ...
535           [% END %]
536
537       The automagic promotion of scalars to single item lists means that you
538       can also use list virtual methods safely, even if you only get one item
539       returned.  For example:
540
541           [% something.first   %]
542           [% something.join    %]
543           [% something.reverse.join(', ') %]
544
545       Note that this is very much a last-ditch behaviour.  If the single item
546       return is an object with a "first" method, for example, then that will
547       be called, as expected, in preference to the list virtual method.
548

Defining Custom Virtual Methods

550       You can define your own virtual methods for scalars, lists and hash
551       arrays.  The Template::Stash package variables $SCALAR_OPS, $LIST_OPS
552       and $HASH_OPS are references to hash arrays that define these virtual
553       methods.  "HASH_OPS" and "LIST_OPS" methods are subroutines that accept
554       a hash/list reference as the first item. "SCALAR_OPS" are subroutines
555       that accept a scalar value as the first item. Any other arguments
556       specified when the method is called will be passed to the subroutine.
557
558           # load Template::Stash to make method tables visible
559           use Template::Stash;
560
561           # define list method to return new list of odd numbers only
562           $Template::Stash::LIST_OPS->{ odd } = sub {
563               my $list = shift;
564               return [ grep { $_ % 2 } @$list ];
565           };
566
567       Example template:
568
569           [% primes = [ 2, 3, 5, 7, 9 ] %]
570           [% primes.odd.join(', ') %]         # 3, 5, 7, 9
571
572       TODO: document the define_vmethod() method which makes this even easier
573
574
575
576perl v5.12.0                      2009-07-04     Template::Manual::VMethods(3)
Impressum