1Template::Manual::VMethUosdesr(3C)ontributed Perl DocumeTnetmaptliaotne::Manual::VMethods(3)
2
3
4
6 Template::Manual::VMethods - Virtual Methods
7
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 strings.
181
182 [% FOREACH dir IN mypath.split(':') %]
183 [% dir %]
184 [% END %]
185
186 substr(offset, length, replacement)
187 Returns a substring starting at "offset", for "length" characters.
188
189 [% str 'foo bar baz wiz waz woz') %]
190 [% str.substr(4, 3) %] # bar
191
192 If "length" is not specified then it returns everything from the
193 "offset" to the end of the string.
194
195 [% str.substr(12) %] # wiz waz woz
196
197 If both "length" and "replacement" are specified, then the method
198 replaces everything from "offset" for "length" characters with
199 $replacement. The substring removed from the string is then returned.
200
201 [% str.substr(0, 11, 'FOO') %] # foo bar baz
202 [% str %] # FOO wiz waz woz
203
204 squote
205 Returns the text with any single quote characters escaped with a
206 backslash prefix.
207
208 [% tim = "Tim O'Reilly" %]
209 [% tim.squote %] # Tim O\'Reilly
210
211 trim
212 Returns the text with any leading and trailing whitespace removed.
213
214 [% text = ' hello world ' %]
215 [% text.trim %] # hello world
216
217 ucfirst
218 Returns the text with the first letter converted to upper case.
219
220 [% word = 'bird' %]
221 [% word.ucfirst %] # Bird
222
223 upper
224 Returns the text in upper case.
225
226 [% word = 'bird' %]
227 [% word.upper %] # BIRD
228
230 keys
231 Returns a list of keys in the hash. They are not returned in any
232 particular order, but the order is the same as for the corresponding
233 values method.
234
235 [% FOREACH key IN hash.keys %]
236 * [% key %]
237 [% END %]
238
239 If you want the keys in sorted order, use the list "sort" method.
240
241 [% FOREACH key IN hash.keys.sort %]
242 * [% key %]
243 [% END %]
244
245 Having got the keys in sorted order, you can then use variable
246 interpolation to fetch the value. This is shown in the following
247 example by the use of $key to fetch the item from "hash" whose key is
248 stored in the "key" variable.
249
250 [% FOREACH key IN hash.keys.sort %]
251 * [% key %] = [% hash.$key %]
252 [% END %]
253
254 Alternately, you can use the "pairs" method to get a list of key/value
255 pairs in sorted order.
256
257 values
258 Returns a list of the values in the hash. As with the "keys" method,
259 they are not returned in any particular order, although it is the same
260 order that the keys are returned in.
261
262 [% hash.values.join(', ') %]
263
264 items
265 Returns a list of both the keys and the values expanded into a single
266 list.
267
268 [% hash = {
269 a = 10
270 b = 20
271 };
272
273 hash.items.join(', ') # a, 10, b, 20
274 %]
275
276 each
277 This method currently returns the same thing as the "items" method.
278
279 However, please note that this method will change in the next major
280 version of the Template Toolkit (v3) to return the same thing as the
281 "pairs" method. This will be done in an effort to make these virtual
282 method more consistent with each other and how Perl works.
283
284 In anticipation of this, we recommend that you stop using "hash.each"
285 and instead use "hash.items".
286
287 pairs
288 This method returns a list of key/value pairs. They are returned in
289 sorted order according to the keys.
290
291 [% FOREACH pair IN product.pairs %]
292 * [% pair.key %] is [% pair.value %]
293 [% END %]
294
295 list
296 Returns the contents of the hash in list form. An argument can be
297 passed to indicate the desired items required in the list: "keys" to
298 return a list of the keys (same as "hash.keys"), "values" to return a
299 list of the values (same as "hash.values"), "each" to return as list of
300 key and values (same as "hash.each"), or "pairs" to return a list of
301 key/value pairs (same as "hash.pairs").
302
303 [% keys = hash.list('keys') %]
304 [% values = hash.list('values') %]
305 [% items = hash.list('each') %]
306 [% pairs = hash.list('pairs') %]
307
308 When called without an argument it currently returns the same thing as
309 the "pairs" method. However, please note that this method will change
310 in the next major version of the Template Toolkit (v3) to return a
311 reference to a list containing the single hash reference (as per the
312 scalar list method).
313
314 In anticipation of this, we recommend that you stop using "hash.list"
315 and instead use "hash.pairs".
316
317 sort, nsort
318 Return a list of the keys, sorted alphabetically ("sort") or
319 numerically ("nsort") according to the corresponding values in the
320 hash.
321
322 [% FOREACH n IN phones.sort %]
323 [% phones.$n %] is [% n %],
324 [% END %]
325
326 import
327 The "import" method can be called on a hash array to import the
328 contents of another hash array.
329
330 [% hash1 = {
331 foo = 'Foo'
332 bar = 'Bar'
333 }
334 hash2 = {
335 wiz = 'Wiz'
336 woz = 'Woz'
337 }
338 %]
339
340 [% hash1.import(hash2) %]
341 [% hash1.wiz %] # Wiz
342
343 You can also call the import() method by itself to import a hash array
344 into the current namespace hash.
345
346 [% user = { id => 'lwall', name => 'Larry Wall' } %]
347 [% import(user) %]
348 [% id %]: [% name %] # lwall: Larry Wall
349
350 defined, exists
351 Returns a true or false value if an item in the hash denoted by the key
352 passed as an argument is defined or exists, respectively.
353
354 [% hash.defined('somekey') ? 'yes' : 'no' %]
355 [% hash.exists('somekey') ? 'yes' : 'no' %]
356
357 When called without any argument, "hash.defined" returns true if the
358 hash itself is defined (e.g. the same effect as "scalar.defined").
359
360 delete
361 Delete one or more items from the hash.
362
363 [% hash.delete('foo', 'bar') %]
364
365 size
366 Returns the number of key/value pairs in the hash.
367
368 empty
369 Returns true if the hash is empty:
370
371 [% IF config.empty %]
372 No configuration available
373 [% END %]
374
375 item
376 Returns an item from the hash using a key passed as an argument.
377
378 [% hash.item('foo') %] # same as hash.foo
379
381 first, last
382 Returns the first/last item in the list. The item is not removed from
383 the list.
384
385 [% results.first %] to [% results.last %]
386
387 If either is given a numeric argument "n", they return the first or
388 last "n" elements:
389
390 The first 5 results are [% results.first(5).join(", ") %].
391
392 size, max
393 Returns the size of a list (number of elements) and the maximum index
394 number (size - 1), respectively.
395
396 [% results.size %] search results matched your query
397
398 empty
399 Returns true if the list is empty:
400
401 [% IF results.empty %]
402 No results found
403 [% END %]
404
405 defined
406 Returns a true or false value if the item in the list denoted by the
407 argument is defined.
408
409 [% list.defined(3) ? 'yes' : 'no' %]
410
411 When called without any argument, "list.defined" returns true if the
412 list itself is defined (e.g. the same effect as "scalar.defined").
413
414 reverse
415 Returns the items of the list in reverse order.
416
417 [% FOREACH s IN scores.reverse %]
418 ...
419 [% END %]
420
421 join
422 Joins the items in the list into a single string, using Perl's join()
423 function.
424
425 [% items.join(', ') %]
426
427 grep
428 Returns a list of the items in the list that match a regular expression
429 pattern.
430
431 [% FOREACH directory.files.grep('\.txt$') %]
432 ...
433 [% END %]
434
435 sort, nsort
436 Returns the items in alpha ("sort") or numerical ("nsort") order.
437
438 [% library = books.sort %]
439
440 An argument can be provided to specify a search key. Where an item in
441 the list is a hash reference, the search key will be used to retrieve a
442 value from the hash which will then be used as the comparison value.
443 Where an item is an object which implements a method of that name, the
444 method will be called to return a comparison value.
445
446 [% library = books.sort('author') %]
447
448 In the example, the "books" list can contains hash references with an
449 "author" key or objects with an "author" method.
450
451 You can also specify multiple sort keys.
452
453 [% library = books.sort('author', 'title') %]
454
455 In this case the books will be sorted primarily by author. If two or
456 more books have authors with the same name then they will be sorted by
457 title.
458
459 unshift(item), push(item)
460 The push() method adds an item or items to the end of list.
461
462 [% mylist.push(foo) %]
463 [% mylist.push(foo, bar) %]
464
465 The unshift() method adds an item or items to the start of a list.
466
467 [% mylist.unshift(foo) %]
468 [% mylist.push(foo, bar) %]
469
470 shift, pop
471 Removes the first/last item from the list and returns it.
472
473 [% first = mylist.shift %]
474 [% last = mylist.pop %]
475
476 unique
477 Returns a list of the unique elements in a list, in the same order as
478 in the list itself.
479
480 [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
481 [% numbers = mylist.unique %]
482
483 While this can be explicitly sorted, it is not required that the list
484 be sorted before the unique elements are pulled out (unlike the Unix
485 command line utility).
486
487 [% numbers = mylist.unique.sort %]
488
489 import
490 Appends the contents of one or more other lists to the end of the
491 current list.
492
493 [% one = [ 1 2 3 ];
494 two = [ 4 5 6 ];
495 three = [ 7 8 9 ];
496 one.import(two, three);
497 one.join(', '); # 1, 2, 3, 4, 5, 6, 7, 8, 9
498 %]
499
500 Import also allows chaining. The below syntax is equivalent.
501
502 [% one = [ 1 2 3 ];
503 two = [ 4 5 6 ];
504 three = [ 7 8 9 ];
505 one.import(two, three).join(', '); # 1, 2, 3, 4, 5, 6, 7, 8, 9
506 # or: one.import(two).import(three).join(', '); # 1, 2, 3, 4, 5, 6, 7, 8, 9
507 %]
508
509 merge
510 Returns a list composed of zero or more other lists:
511
512 [% list_one = [ 1 2 3 ];
513 list_two = [ 4 5 6 ];
514 list_three = [ 7 8 9 ];
515 list_four = list_one.merge(list_two, list_three);
516 %]
517
518 The original lists are not modified.
519
520 slice(from, to)
521 Returns a slice of items in the list between the bounds passed as
522 arguments. If the second argument, "to", isn't specified, then it
523 defaults to the last item in the list. The original list is not
524 modified.
525
526 [% first_three = list.slice(0,2) %]
527 [% last_three = list.slice(-3, -1) %]
528
529 splice(offset, length, list)
530 Behaves just like Perl's splice() function allowing you to selectively
531 remove and/or replace elements in a list. It removes "length" items
532 from the list, starting at "offset" and replaces them with the items in
533 "list".
534
535 [% play_game = [ 'play', 'scrabble' ];
536 ping_pong = [ 'ping', 'pong' ];
537 redundant = play_game.splice(1, 1, ping_pong);
538 redundant.join; # scrabble
539 play_game.join; # play ping pong
540 %]
541
542 The method returns a list of the items removed by the splice. You can
543 use the "CALL" directive to ignore the output if you're not planning to
544 do anything with it.
545
546 [% CALL play_game.splice(1, 1, ping_pong) %]
547
548 As well as providing a reference to a list of replacement values, you
549 can pass in a list of items.
550
551 [% CALL list.splice(-1, 0, 'foo', 'bar') %]
552
553 Be careful about passing just one item in as a replacement value. If
554 it is a reference to a list then the contents of the list will be used.
555 If it's not a list, then it will be treated as a single value. You can
556 use square brackets around a single item if you need to be explicit:
557
558 [% # push a single item, an_item
559 CALL list.splice(-1, 0, an_item);
560
561 # push the items from another_list
562 CALL list.splice(-1, 0, another_list);
563
564 # push a reference to another_list
565 CALL list.splice(-1, 0, [ another_list ]);
566 %]
567
568 hash
569 Returns a reference to a hash array comprised of the elements in the
570 list. The even-numbered elements (0, 2, 4, etc) become the keys and
571 the odd-numbered elements (1, 3, 5, etc) the values.
572
573 [% list = ['pi', 3.14, 'e', 2.718] %]
574 [% hash = list.hash %]
575 [% hash.pi %] # 3.14
576 [% hash.e %] # 2.718
577
578 If a numerical argument is provided then the hash returned will have
579 keys generated for each item starting at the number specified.
580
581 [% list = ['beer', 'peanuts'] %]
582 [% hash = list.hash(1) %]
583 [% hash.1 %] # beer
584 [% hash.2 %] # peanuts
585
586 item
587 Returns an item from the list using an index passed as an argument.
588
589 [% list.item(0) %] # same as list.0
590
592 In addition to the scalar virtual methods listed in the previous
593 section, you can also call any list virtual method against a scalar.
594 The item will be automagically promoted to a single element list and
595 the appropriate list virtual method will be called.
596
597 One particular benefit of this comes when calling subroutines or object
598 methods that return a list of items, rather than the preferred
599 reference to a list of items. In this case, the Template Toolkit
600 automatically folds the items returned into a list.
601
602 The upshot is that you can continue to use existing Perl modules or
603 code that returns lists of items, without having to refactor it just to
604 keep the Template Toolkit happy (by returning references to list).
605 "Class::DBI" module is just one example of a particularly useful module
606 which returns values this way.
607
608 If only a single item is returned from a subroutine then the Template
609 Toolkit assumes it meant to return a single item (rather than a list of
610 1 item) and leaves it well alone, returning the single value as it is.
611 If you're executing a database query, for example, you might get 1 item
612 returned, or perhaps many items which are then folded into a list.
613
614 The "FOREACH" directive will happily accept either a list or a single
615 item which it will treat as a list. So it's safe to write directives
616 like this, where we assume that the "something" variable is bound to a
617 subroutine which may return one or more items:
618
619 [% FOREACH item IN something %]
620 ...
621 [% END %]
622
623 The automagic promotion of scalars to single item lists means that you
624 can also use list virtual methods safely, even if you only get one item
625 returned. For example:
626
627 [% something.first %]
628 [% something.join %]
629 [% something.reverse.join(', ') %]
630
631 Note that this is very much a last-ditch behaviour. If the single item
632 return is an object with a "first" method, for example, then that will
633 be called, as expected, in preference to the list virtual method.
634
636 You can define your own virtual methods for scalars, lists and hash
637 arrays. The Template::Stash package variables $SCALAR_OPS, $LIST_OPS
638 and $HASH_OPS are references to hash arrays that define these virtual
639 methods. "HASH_OPS" and "LIST_OPS" methods are subroutines that accept
640 a hash/list reference as the first item. "SCALAR_OPS" are subroutines
641 that accept a scalar value as the first item. Any other arguments
642 specified when the method is called will be passed to the subroutine.
643
644 # load Template::Stash to make method tables visible
645 use Template::Stash;
646
647 # define list method to return new list of odd numbers only
648 $Template::Stash::LIST_OPS->{ odd } = sub {
649 my $list = shift;
650 return [ grep { $_ % 2 } @$list ];
651 };
652
653 Example template:
654
655 [% primes = [ 2, 3, 5, 7, 9 ] %]
656 [% primes.odd.join(', ') %] # 3, 5, 7, 9
657
658 TODO: document the define_vmethod() method which makes this even easier
659
660
661
662perl v5.36.0 2023-01-20 Template::Manual::VMethods(3)