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

Hash Virtual Methods

224   keys
225       Returns a list of keys in the hash.  They are not returned in any
226       particular order, but the order is the same as for the corresponding
227       values method.
228
229           [% FOREACH key IN hash.keys %]
230              * [% key %]
231           [% END %]
232
233       If you want the keys in sorted order, use the list "sort" method.
234
235           [% FOREACH key IN hash.keys.sort %]
236              * [% key %]
237           [% END %]
238
239       Having got the keys in sorted order, you can then use variable
240       interpolation to fetch the value.  This is shown in the following
241       example by the use of $key to fetch the item from "hash" whose key is
242       stored in the "key" variable.
243
244           [% FOREACH key IN hash.keys.sort %]
245              * [% key %] = [% hash.$key %]
246           [% END %]
247
248       Alternately, you can use the "pairs" method to get a list of key/value
249       pairs in sorted order.
250
251   values
252       Returns a list of the values in the hash.  As with the "keys" method,
253       they are not returned in any particular order, although it is the same
254       order that the keys are returned in.
255
256           [% hash.values.join(', ') %]
257
258   items
259       Returns a list of both the keys and the values expanded into a single
260       list.
261
262           [% hash = {
263                 a = 10
264                 b = 20
265              };
266
267              hash.items.join(', ')    # a, 10, b, 20
268           %]
269
270   each
271       This method currently returns the same thing as the "items" method.
272
273       However, please note that this method will change in the next major
274       version of the Template Toolkit (v3) to return the same thing as the
275       "pairs" method.  This will be done in an effort to make these virtual
276       method more consistent with each other and how Perl works.
277
278       In anticipation of this, we recommend that you stop using "hash.each"
279       and instead use "hash.items".
280
281   pairs
282       This method returns a list of key/value pairs.  They are returned in
283       sorted order according to the keys.
284
285           [% FOREACH pair IN product.pairs %]
286              * [% pair.key %] is [% pair.value %]
287           [% END %]
288
289   list
290       Returns the contents of the hash in list form.  An argument can be
291       passed to indicate the desired items required in the list: "keys" to
292       return a list of the keys (same as "hash.keys"), "values" to return a
293       list of the values (same as "hash.values"), "each" to return as list of
294       key and values (same as "hash.each"), or "pairs" to return a list of
295       key/value pairs (same as "hash.pairs").
296
297           [% keys   = hash.list('keys') %]
298           [% values = hash.list('values') %]
299           [% items  = hash.list('each') %]
300           [% pairs  = hash.list('pairs') %]
301
302       When called without an argument it currently returns the same thing as
303       the "pairs" method.  However, please note that this method will change
304       in the next major version of the Template Toolkit (v3) to return a
305       reference to a list containing the single hash reference (as per the
306       scalar list method).
307
308       In anticipation of this, we recommend that you stop using "hash.list"
309       and instead use "hash.pairs".
310
311   sort, nsort
312       Return a list of the keys, sorted alphabetically ("sort") or
313       numerically ("nsort") according to the corresponding values in the
314       hash.
315
316           [% FOREACH n IN phones.sort %]
317              [% phones.$n %] is [% n %],
318           [% END %]
319
320   import
321       The "import" method can be called on a hash array to import the
322       contents of another hash array.
323
324           [% hash1 = {
325                foo = 'Foo'
326                bar = 'Bar'
327              }
328              hash2 = {
329                  wiz = 'Wiz'
330                  woz = 'Woz'
331              }
332           %]
333
334           [% hash1.import(hash2) %]
335           [% hash1.wiz %]             # Wiz
336
337       You can also call the "import()" method by itself to import a hash
338       array into the current namespace hash.
339
340           [% user = { id => 'lwall', name => 'Larry Wall' } %]
341           [% import(user) %]
342           [% id %]: [% name %]        # lwall: Larry Wall
343
344   defined, exists
345       Returns a true or false value if an item in the hash denoted by the key
346       passed as an argument is defined or exists, respectively.
347
348           [% hash.defined('somekey') ? 'yes' : 'no' %]
349           [% hash.exists('somekey') ? 'yes' : 'no' %]
350
351       When called without any argument, "hash.defined" returns true if the
352       hash itself is defined (e.g. the same effect as "scalar.defined").
353
354   delete
355       Delete one or more items from the hash.
356
357           [% hash.delete('foo', 'bar') %]
358
359   size
360       Returns the number of key/value pairs in the hash.
361
362   item
363       Returns an item from the hash using a key passed as an argument.
364
365           [% hash.item('foo') %]  # same as hash.foo
366

List Virtual Methods

368   first, last
369       Returns the first/last item in the list.  The item is not removed from
370       the list.
371
372           [% results.first %] to [% results.last %]
373
374       If either is given a numeric argument "n", they return the first or
375       last "n" elements:
376
377           The first 5 results are [% results.first(5).join(", ") %].
378
379   size, max
380       Returns the size of a list (number of elements) and the maximum index
381       number (size - 1), respectively.
382
383           [% results.size %] search results matched your query
384
385   defined
386       Returns a true or false value if the item in the list denoted by the
387       argument is defined.
388
389           [% list.defined(3) ? 'yes' : 'no' %]
390
391       When called without any argument, "list.defined" returns true if the
392       list itself is defined (e.g. the same effect as "scalar.defined").
393
394   reverse
395       Returns the items of the list in reverse order.
396
397           [% FOREACH s IN scores.reverse %]
398              ...
399           [% END %]
400
401   join
402       Joins the items in the list into a single string, using Perl's "join()"
403       function.
404
405           [% items.join(', ') %]
406
407   grep
408       Returns a list of the items in the list that match a regular expression
409       pattern.
410
411           [% FOREACH directory.files.grep('\.txt$') %]
412              ...
413           [% END %]
414
415   sort, nsort
416       Returns the items in alpha ("sort") or numerical ("nsort") order.
417
418           [% library = books.sort %]
419
420       An argument can be provided to specify a search key.  Where an item in
421       the list is a hash reference, the search key will be used to retrieve a
422       value from the hash which will then be used as the comparison value.
423       Where an item is an object which implements a method of that name, the
424       method will be called to return a comparison value.
425
426           [% library = books.sort('author') %]
427
428       In the example, the "books" list can contains hash references with an
429       "author" key or objects with an "author" method.
430
431       You can also specify multiple sort keys.
432
433           [% library = books.sort('author', 'title') %]
434
435       In this case the books will be sorted primarily by author.  If two or
436       more books have authors with the same name then they will be sorted by
437       title.
438
439   unshift(item), push(item)
440       The "push()" method adds an item or items to the end of list.
441
442           [% mylist.push(foo) %]
443           [% mylist.push(foo, bar) %]
444
445       The "unshift()" method adds an item or items to the start of a list.
446
447           [% mylist.unshift(foo) %]
448           [% mylist.push(foo, bar)    %]
449
450   shift, pop
451       Removes the first/last item from the list and returns it.
452
453           [% first = mylist.shift %]
454           [% last  = mylist.pop   %]
455
456   unique
457       Returns a list of the unique elements in a list, in the same order as
458       in the list itself.
459
460           [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
461           [% numbers = mylist.unique %]
462
463       While this can be explicitly sorted, it is not required that the list
464       be sorted before the unique elements are pulled out (unlike the Unix
465       command line utility).
466
467           [% numbers = mylist.unique.sort %]
468
469   import
470       Appends the contents of one or more other lists to the end of the
471       current list.
472
473           [% one   = [ 1 2 3 ];
474              two   = [ 4 5 6 ];
475              three = [ 7 8 9 ];
476              one.import(two, three);
477              one.join(', );     # 1, 2, 3, 4, 5, 6, 7, 8, 9
478           %]
479
480   merge
481       Returns a list composed of zero or more other lists:
482
483           [% list_one = [ 1 2 3 ];
484              list_two = [ 4 5 6 ];
485              list_three = [ 7 8 9 ];
486              list_four = list_one.merge(list_two, list_three);
487           %]
488
489       The original lists are not modified.
490
491   slice(from, to)
492       Returns a slice of items in the list between the bounds passed as
493       arguments.  If the second argument, "to", isn't specified, then it
494       defaults to the last item in the list.  The original list is not
495       modified.
496
497           [% first_three = list.slice(0,2) %]
498           [% last_three  = list.slice(-3, -1) %]
499
500   splice(offset, length, list)
501       Behaves just like Perl's "splice()" function allowing you to
502       selectively remove and/or replace elements in a list.  It removes
503       "length" items from the list, starting at "offset" and replaces them
504       with the items in "list".
505
506           [% play_game = [ 'play', 'scrabble' ];
507              ping_pong = [ 'ping', 'pong' ];
508              redundant = play_game.splice(1, 1, ping_pong);
509              redundant.join;     # scrabble
510              play_game.join;     # play ping pong
511           %]
512
513       The method returns a list of the items removed by the splice.  You can
514       use the "CALL" directive to ignore the output if you're not planning to
515       do anything with it.
516
517           [% CALL play_game.splice(1, 1, ping_pong) %]
518
519       As well as providing a reference to a list of replacement values, you
520       can pass in a list of items.
521
522           [% CALL list.splice(-1, 0, 'foo', 'bar') %]
523
524       Be careful about passing just one item in as a replacement value.  If
525       it is a reference to a list then the contents of the list will be used.
526       If it's not a list, then it will be treated as a single value.  You can
527       use square brackets around a single item if you need to be explicit:
528
529           [% # push a single item, an_item
530              CALL list.splice(-1, 0, an_item);
531
532              # push the items from another_list
533              CALL list.splice(-1, 0, another_list);
534
535              # push a reference to another_list
536              CALL list.splice(-1, 0, [ another_list ]);
537           %]
538
539   hash
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

Automagic Promotion of Scalar to List for Virtual Methods

558       In addition to the scalar virtual methods listed in the previous
559       section, you can also call any list virtual method against a scalar.
560       The item will be automagically promoted to a single element list and
561       the appropriate list virtual method will be called.
562
563       One particular benefit of this comes when calling subroutines or object
564       methods that return a list of items, rather than the preferred
565       reference to a list of items.  In this case, the Template Toolkit
566       automatically folds the items returned into a list.
567
568       The upshot is that you can continue to use existing Perl modules or
569       code that returns lists of items, without having to refactor it just to
570       keep the Template Toolkit happy (by returning references to list).
571       "Class::DBI" module is just one example of a particularly useful module
572       which returns values this way.
573
574       If only a single item is returned from a subroutine then the Template
575       Toolkit assumes it meant to return a single item (rather than a list of
576       1 item) and leaves it well alone, returning the single value as it is.
577       If you're executing a database query, for example, you might get 1 item
578       returned, or perhaps many items which are then folded into a list.
579
580       The "FOREACH" directive will happily accept either a list or a single
581       item which it will treat as a list. So it's safe to write directives
582       like this, where we assume that the "something" variable is bound to a
583       subroutine which may return one or more items:
584
585           [% FOREACH item IN something %]
586              ...
587           [% END %]
588
589       The automagic promotion of scalars to single item lists means that you
590       can also use list virtual methods safely, even if you only get one item
591       returned.  For example:
592
593           [% something.first   %]
594           [% something.join    %]
595           [% something.reverse.join(', ') %]
596
597       Note that this is very much a last-ditch behaviour.  If the single item
598       return is an object with a "first" method, for example, then that will
599       be called, as expected, in preference to the list virtual method.
600

Defining Custom Virtual Methods

602       You can define your own virtual methods for scalars, lists and hash
603       arrays.  The Template::Stash package variables $SCALAR_OPS, $LIST_OPS
604       and $HASH_OPS are references to hash arrays that define these virtual
605       methods.  "HASH_OPS" and "LIST_OPS" methods are subroutines that accept
606       a hash/list reference as the first item. "SCALAR_OPS" are subroutines
607       that accept a scalar value as the first item. Any other arguments
608       specified when the method is called will be passed to the subroutine.
609
610           # load Template::Stash to make method tables visible
611           use Template::Stash;
612
613           # define list method to return new list of odd numbers only
614           $Template::Stash::LIST_OPS->{ odd } = sub {
615               my $list = shift;
616               return [ grep { $_ % 2 } @$list ];
617           };
618
619       Example template:
620
621           [% primes = [ 2, 3, 5, 7, 9 ] %]
622           [% primes.odd.join(', ') %]         # 3, 5, 7, 9
623
624       TODO: document the define_vmethod() method which makes this even easier
625
626
627
628perl v5.16.3                      2012-02-07     Template::Manual::VMethods(3)
Impressum