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   empty
72       Returns true if the string is empty:
73
74           [% IF details.empty %]
75              No details specified
76           [% END %]
77
78   list
79       Return the value as a single element list.  This can be useful if you
80       have a variable which may contain a single item or a list and you want
81       to treat them equally.  The "list" method can be called against a list
82       reference and will simply return the original reference, effectively a
83       no-op.
84
85           [% thing.list.size %]     # thing can be a scalar or a list
86
87   lower
88       Returns the text in lower case.
89
90           [% word = 'BIRD' %]
91           [% word.lower %]          # bird
92
93   match(pattern, global)
94       Performs a regular expression match on the string using the pattern
95       passed as an argument.  If the pattern matches the string then the
96       method returns a reference to a list of any strings captured within
97       parenthesis in the pattern.
98
99           [% name = 'Larry Wall' %]
100           [% matches = name.match('(\w+) (\w+)') %]
101           [% matches.1 %], [% matches.0 %]    # Wall, Larry
102
103       If the pattern does not match then the method returns false, rather
104       than returning an empty list which Perl and the Template Toolkit both
105       consider to be a true value.  This allows you to write expression like
106       this.
107
108           [% "We're not worthy!" IF name.match('Larry Wall') %]
109
110           [% IF (matches = name.match('(\w+) (\w+)')) %]
111              pattern matches: [% matches.join(', ') %]
112           [% ELSE %]
113              pattern does not match
114           [% END %]
115
116       Any regex modifiers, like "/s", should be added in the regex using the
117       "(?s)" syntax.  For example, to modify the regex to disregard
118       whitespace (the "/x" switch), use:
119
120           [% re = '(?x)
121                      (\w+)
122                      [ ]
123                      (\w+)
124                    ';
125             matches = name.match(re);
126           %]
127
128       To perform a global search to match the pattern as many times as it
129       appears in the source string, provide a true value for the "global"
130       argument following the pattern.
131
132           [% text = 'bandanna';
133              text.match('an+', 1).join(', ')      # an, ann
134           %]
135
136   repeat(n)
137       Repeat the string a specified number of times.
138
139           [% name = 'foo' %]
140           [% name.repeat(3) %]                # foofoofoo
141
142   replace(search, replace)
143       Outputs the string with all instances of the first argument (specified
144       as a Perl regular expression) with the second.
145
146           [% name = 'foo, bar & baz' %]
147           [% name.replace('\W+', '_') %]        # foo_bar_baz
148
149       You can use $1, $2, etc., to reference captured parts (in parentheses)
150       in the regular expression.  Just be careful to single quote the
151       replacement string.  If you use double quotes then TT will try and
152       interpolate the variables before passing the string to the "replace"
153       vmethod.
154
155           [% name = 'FooBarBaz' %]
156           [% name.replace('([A-Z])', ' $1') %]  # Foo Bar Baz
157
158   remove(pattern)
159       Outputs the string with all instances of the pattern (specified as a
160       Perl regular expression) removed.
161
162           [% name = 'foo, bar & baz' %]
163           [% name.remove('\W+') %]    # foobarbaz
164
165   search(pattern)
166       Performs a similar function to match but simply returns true if the
167       string matches the regular expression pattern passed as an argument.
168
169           [% name = 'foo bar baz' %]
170           [% name.search('bar') ? 'bar' : 'no bar' %]     # bar
171
172       This virtual method is now deprecated in favour of match.  Move along
173       now, there's nothing more to see here.
174
175   size
176       Always returns 1 for scalar values.  This method is provided for
177       consistency with the hash and list size methods.
178
179   split(pattern)
180       Calls Perl's "split()" function to split a string into a list of
181       strings.
182
183           [% FOREACH dir IN mypath.split(':') %]
184              [% dir %]
185           [% END %]
186
187   substr(offset, length, replacement)
188       Returns a substring starting at "offset", for "length" characters.
189
190           [% str 'foo bar baz wiz waz woz') %]
191           [% str.substr(4, 3) %]    # bar
192
193       If "length" is not specified then it returns everything from the
194       "offset" to the end of the string.
195
196           [% str.substr(12) %]      # wiz waz woz
197
198       If both "length" and "replacement" are specified, then the method
199       replaces everything from "offset" for "length" characters with
200       $replacement.  The substring removed from the string is then returned.
201
202           [% str.substr(0, 11, 'FOO') %]   # foo bar baz
203           [% str %]                        # FOO wiz waz woz
204
205   squote
206       Returns the text with any single quote characters escaped with a
207       backslash prefix.
208
209           [% tim = "Tim O'Reilly" %]
210           [% tim.squote %]          # Tim O\'Reilly
211
212   trim
213       Returns the text with any leading and trailing whitespace removed.
214
215           [% text = '  hello  world  ' %]
216           [% text.trim %]           # hello  world
217
218   ucfirst
219       Returns the text with the first letter converted to upper case.
220
221           [% word = 'bird' %]
222           [% word.ucfirst %]        # Bird
223
224   upper
225       Returns the text in upper case.
226
227           [% word = 'bird' %]
228           [% word.upper %]          # BIRD
229

Hash Virtual Methods

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

List Virtual Methods

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

Automagic Promotion of Scalar to List for Virtual Methods

593       In addition to the scalar virtual methods listed in the previous
594       section, you can also call any list virtual method against a scalar.
595       The item will be automagically promoted to a single element list and
596       the appropriate list virtual method will be called.
597
598       One particular benefit of this comes when calling subroutines or object
599       methods that return a list of items, rather than the preferred
600       reference to a list of items.  In this case, the Template Toolkit
601       automatically folds the items returned into a list.
602
603       The upshot is that you can continue to use existing Perl modules or
604       code that returns lists of items, without having to refactor it just to
605       keep the Template Toolkit happy (by returning references to list).
606       "Class::DBI" module is just one example of a particularly useful module
607       which returns values this way.
608
609       If only a single item is returned from a subroutine then the Template
610       Toolkit assumes it meant to return a single item (rather than a list of
611       1 item) and leaves it well alone, returning the single value as it is.
612       If you're executing a database query, for example, you might get 1 item
613       returned, or perhaps many items which are then folded into a list.
614
615       The "FOREACH" directive will happily accept either a list or a single
616       item which it will treat as a list. So it's safe to write directives
617       like this, where we assume that the "something" variable is bound to a
618       subroutine which may return one or more items:
619
620           [% FOREACH item IN something %]
621              ...
622           [% END %]
623
624       The automagic promotion of scalars to single item lists means that you
625       can also use list virtual methods safely, even if you only get one item
626       returned.  For example:
627
628           [% something.first   %]
629           [% something.join    %]
630           [% something.reverse.join(', ') %]
631
632       Note that this is very much a last-ditch behaviour.  If the single item
633       return is an object with a "first" method, for example, then that will
634       be called, as expected, in preference to the list virtual method.
635

Defining Custom Virtual Methods

637       You can define your own virtual methods for scalars, lists and hash
638       arrays.  The Template::Stash package variables $SCALAR_OPS, $LIST_OPS
639       and $HASH_OPS are references to hash arrays that define these virtual
640       methods.  "HASH_OPS" and "LIST_OPS" methods are subroutines that accept
641       a hash/list reference as the first item. "SCALAR_OPS" are subroutines
642       that accept a scalar value as the first item. Any other arguments
643       specified when the method is called will be passed to the subroutine.
644
645           # load Template::Stash to make method tables visible
646           use Template::Stash;
647
648           # define list method to return new list of odd numbers only
649           $Template::Stash::LIST_OPS->{ odd } = sub {
650               my $list = shift;
651               return [ grep { $_ % 2 } @$list ];
652           };
653
654       Example template:
655
656           [% primes = [ 2, 3, 5, 7, 9 ] %]
657           [% primes.odd.join(', ') %]         # 3, 5, 7, 9
658
659       TODO: document the define_vmethod() method which makes this even easier
660
661
662
663perl v5.32.1                      2021-01-27     Template::Manual::VMethods(3)
Impressum