1Template::Manual::VMethUosdesr(3C)ontributed Perl DocumeTnetmaptliaotne::Manual::VMethods(3)
2
3
4
6 Template::Manual::VMethods - Virtual Methods
7
9 Scalar Virtual Methods
10
11 defined
12 Returns true if the value is defined.
13
14 [% user = get_user(uid) IF uid.defined %]
15
16 length
17 Returns the length of the string representation of the item:
18
19 [% IF password.length < 8 %]
20 Password too short, dumbass!
21 [% END %]
22
23 repeat(n)
24 Repeat the string a specified number of times.
25
26 [% name = 'foo' %]
27 [% name.repeat(3) %] # foofoofoo
28
29 replace(search, replace)
30 Outputs the string with all instances of the first argument (speci‐
31 fied as a Perl regular expression) with the second.
32
33 [% name = 'foo, bar & baz' %]
34 [% name.replace('\W+', '_') %] # foo_bar_baz
35
36 remove(pattern)
37 Outputs the string with all instances of the pattern (specified as
38 a Perl regular expression) removed.
39
40 [% name = 'foo, bar & baz' %]
41 [% name.remove('\W+') %] # foobarbaz
42
43 match(pattern, global)
44 Performs a regular expression match on the string using the pattern
45 passed as an argument. If the pattern matches the string then the
46 method returns a reference to a list of any strings captured within
47 parenthesis in the pattern.
48
49 [% name = 'Larry Wall' %]
50 [% matches = name.match('(\w+) (\w+)') %]
51 [% matches.1 %], [% matches.0 %] # Wall, Larry
52
53 If the pattern does not match then the method returns false, rather
54 than returning an empty list which Perl and the Template Toolkit
55 both consider to be a true value. This allows you to write expres‐
56 sion like this.
57
58 [% "We're not worthy!" IF name.match('Larry Wall') %]
59
60 [% IF (matches = name.match('(\w+) (\w+)')) %]
61 pattern matches: [% matches.join(', ') %]
62 [% ELSE %]
63 pattern does not match
64 [% END %]
65
66 Any regex modifiers, like "/s", should be added in the regex using
67 the "(?s)" syntax. For example, to modify the regex to disregard
68 whitespace (the "/x" switch), use:
69
70 [% re = '(?x)
71 (\w+)
72 [ ]
73 (\w+)
74 ';
75 matches = name.match(re);
76 %]
77
78 To perform a global search to match the pattern as many times as it
79 appears in the source string, provide a true value for the 'global'
80 argument following the pattern.
81
82 [% text = 'bandanna';
83 text.match('an+', 1).join(', ) # an, ann
84 %]
85
86 search(pattern)
87 Performs a similar function to 'match' but simply returns true if
88 the string matches the regular expression pattern passed as an
89 argument.
90
91 [% name = 'foo bar baz' %]
92 [% name.search('bar') ? 'bar' : 'no bar' %] # bar
93
94 This virtual method is now deprecated in favour of 'match'. Move
95 along now, there's nothing more to see here.
96
97 split(pattern)
98 Calls Perl's split() function to split a string into a list of
99 strings.
100
101 [% FOREACH dir = mypath.split(':') %]
102 [% dir %]
103 [% END %]
104
105 chunk(size)
106 Splits the value into a list of chunks of a certain size.
107
108 [% ccard_no = "1234567824683579";
109 ccard_no.chunk(4).join
110 %]
111
112 Output:
113
114 1234 5678 2468 3579
115
116 If the size is specified as a negative number then the text will be
117 chunked from right-to-left. This gives the correct grouping for
118 numbers, for example.
119
120 [% number = 1234567;
121 number.chunk(-3).join(',')
122 %]
123
124 Output:
125
126 1,234,567
127
128 substr(offset, length, replacement)
129 Returns a substring starting at 'offset', for 'length' characters.
130
131 [% str 'foo bar baz wiz waz woz') %]
132 [% str.substr(4, 3) %] # bar
133
134 If 'length' is not specified then it returns everything from the
135 'offset' to the end of the string.
136
137 [% str.substr(12) %] # wiz waz woz
138
139 If both 'length' and 'replacement' are specified, then the method
140 replaces everything from 'offset' for 'length' characters with
141 $replacement. The substring removed from the string is then
142 returned.
143
144 [% str.substr(0, 11, 'FOO') %] # foo bar baz
145 [% str %] # FOO wiz waz woz
146
147 list
148 Return the value as a single element list. This can be useful if
149 you have a variable which may contain a single item or a list and
150 you want to treat them equally. The 'list' method can be called
151 against a list reference and will simply return the original refer‐
152 ence, effectively a no-op.
153
154 [% thing.list.size %] # thing can be a scalar or a list
155
156 hash
157 Return the value as a hash reference containing a single entry with
158 the key 'value' indicating the original scalar value. As with the
159 'list' virtual method, this is generally used to help massage data
160 into different formats.
161
162 size
163 Always returns 1 for scalar values. This method is provided for
164 consistency with the hash and list size methods.
165
166 Hash Virtual Methods
167
168 keys
169 Returns a list of keys in the hash. They are not returned in any
170 particular order, but the order is the same as for the correspond‐
171 ing values method.
172
173 [% FOREACH key IN hash.keys %]
174 * [% key %]
175 [% END %]
176
177 If you want the keys in sorted order, use the list 'sort' method.
178
179 [% FOREACH key IN hash.keys.sort %]
180 * [% key %]
181 [% END %]
182
183 Having got the keys in sorted order, you can then use variable
184 interpolation to fetch the value. This is shown in the following
185 example by the use of '$key' to fetch the item from 'hash' whose
186 key is stored in the 'key' variable.
187
188 [% FOREACH key IN hash.keys.sort %]
189 * [% key %] = [% hash.$key %]
190 [% END %]
191
192 Alternately, you can use the 'pairs' method to get a list of
193 key/value pairs in sorted order.
194
195 values
196 Returns a list of the values in the hash. As with the 'keys'
197 method, they are not returned in any particular order, although it
198 is the same order that the keys are returned in.
199
200 [% hash.values.join(', ') %]
201
202 items
203 Returns a list of both the keys and the values expanded into a sin‐
204 gle list.
205
206 [% hash = {
207 a = 10
208 b = 20
209 };
210
211 hash.items.join(', ') # a, 10, b, 20
212 %]
213
214 each
215 This method currently returns the same thing as the 'items' method.
216
217 However, please note that this method will change in the next major
218 version of the Template Toolkit (v3) to return the same thing as
219 the 'pairs' method. This will be done in an effort to make these
220 virtual method more consistent with each other and how Perl works.
221
222 In anticipation of this, we recommend that you stop using
223 'hash.each' and instead use 'hash.items'.
224
225 pairs
226 This method returns a list of key/value pairs. They are returned
227 in sorted order according to the keys.
228
229 [% FOREACH pair IN product.pairs %]
230 * [% pair.key %] is [% pair.value %]
231 [% END %]
232
233 list
234 Returns the contents of the hash in list form. An argument can be
235 passed to indicate the desired items required in the list: 'keys'
236 to return a list of the keys (same as hash.keys), 'values' to
237 return a list of the values (same as hash.values), 'each' to return
238 as list of key and values (same as hash.each), or 'pairs' to return
239 a list of key/value pairs (same as hash.pairs).
240
241 [% keys = hash.list('keys') %]
242 [% values = hash.list('values') %]
243 [% items = hash.list('each') %]
244 [% pairs = hash.list('pairs') %]
245
246 When called without an argument it currently returns the same thing
247 as the 'pairs' method. However, please note that this method will
248 change in the next major version of the Template Toolkit (v3) to
249 return a reference to a list containing the single hash reference
250 (as per the scalar list method).
251
252 In anticipation of this, we recommend that you stop using
253 'hash.list' and instead use 'hash.pairs'.
254
255 sort, nsort
256 Return a list of the keys, sorted alphabetically (sort) or numeri‐
257 cally (nsort) according to the corresponding values in the hash.
258
259 [% FOREACH n = phones.sort %]
260 [% phones.$n %] is [% n %],
261 [% END %]
262
263 import
264 The import method can be called on a hash array to import the con‐
265 tents of another hash array.
266
267 [% hash1 = {
268 foo => 'Foo',
269 bar => 'Bar',
270 }
271 hash2 = {
272 wiz => 'Wiz',
273 woz => 'Woz',
274 }
275 %]
276
277 [% hash1.import(hash2) %]
278 [% hash1.wiz %] # Wiz
279
280 You can also call the import() method by itself to import a hash
281 array into the current namespace hash.
282
283 [% user = { id => 'lwall', name => 'Larry Wall' } %]
284 [% import(user) %]
285 [% id %]: [% name %] # lwall: Larry Wall
286
287 defined, exists
288 Returns a true or false value if an item in the hash denoted by the
289 key passed as an argument is defined or exists, respectively.
290
291 [% hash.defined('somekey') ? 'yes' : 'no' %]
292 [% hash.exists('somekey') ? 'yes' : 'no' %]
293
294 When called without any argument, hash.defined returns true if the
295 hash itself is defined (e.g. the same effect as scalar.defined).
296
297 delete
298 Delete one or more items from the hash.
299
300 [% hash.delete('foo', 'bar') %]
301
302 size
303 Returns the number of key/value pairs in the hash.
304
305 item
306 Returns an item from the hash using a key passed as an argument.
307
308 [% hash.item('foo') %] # same as hash.foo
309
310 List Virtual Methods
311
312 first, last
313 Returns the first/last item in the list. The item is not removed
314 from the list.
315
316 [% results.first %] to [% results.last %]
317
318 If either is given a numeric argument "n", they return the first or
319 last "n" elements:
320
321 The first 5 results are [% results.first(5).join(", ") %].
322
323 size, max
324 Returns the size of a list (number of elements) and the maximum
325 index number (size - 1), respectively.
326
327 [% results.size %] search results matched your query
328
329 defined
330 Returns a true or false value if the item in the list denoted by
331 the argument is defined.
332
333 [% list.defined(3) ? 'yes' : 'no' %]
334
335 When called without any argument, list.defined returns true if the
336 list itself is defined (e.g. the same effect as scalar.defined).
337
338 reverse
339 Returns the items of the list in reverse order.
340
341 [% FOREACH s = scores.reverse %]
342 ...
343 [% END %]
344
345 join
346 Joins the items in the list into a single string, using Perl's join
347 function.
348
349 [% items.join(', ') %]
350
351 grep
352 Returns a list of the items in the list that match a regular
353 expression pattern.
354
355 [% FOREACH directory.files.grep('\.txt$') %]
356 ...
357 [% END %]
358
359 sort, nsort
360 Returns the items in alpha (sort) or numerical (nsort) order.
361
362 [% library = books.sort %]
363
364 An argument can be provided to specify a search key. Where an item
365 in the list is a hash reference, the search key will be used to
366 retrieve a value from the hash which will then be used as the com‐
367 parison value. Where an item is an object which implements a
368 method of that name, the method will be called to return a compari‐
369 son value.
370
371 [% library = books.sort('author') %]
372
373 In the example, the 'books' list can contains hash references with
374 an 'author' key or objects with an 'author' method.
375
376 unshift(item), push(item)
377 The push() method adds an item or items to the end of list.
378
379 [% mylist.push(foo) %]
380 [% mylist.push(foo, bar) %]
381
382 The unshift() method adds an item or items to the start of a list.
383
384 [% mylist.unshift(foo) %]
385 [% mylist.push(foo, bar) %]
386
387 shift, pop
388 Removes the first/last item from the list and returns it.
389
390 [% first = mylist.shift %]
391 [% last = mylist.pop %]
392
393 unique
394 Returns a list of the unique elements in a list, in the same order
395 as in the list itself.
396
397 [% mylist = [ 1, 2, 3, 2, 3, 4, 1, 4, 3, 4, 5 ] %]
398 [% numbers = mylist.unique %]
399
400 While this can be explicitly sorted, it is not required that the
401 list be sorted before the unique elements are pulled out (unlike
402 the Unix command line utility).
403
404 [% numbers = mylist.unique.sort %]
405
406 import
407 Appends the contents of one or more other lists to the end of the
408 current list.
409
410 [% one = [ 1 2 3 ];
411 two = [ 4 5 6 ];
412 three = [ 7 8 9 ];
413
414 one.import(two, three);
415
416 one.join(', ); # 1, 2, 3, 4, 5, 6, 7, 8, 9
417 %]
418
419 merge
420 Returns a list composed of zero or more other lists:
421
422 [% list_one = [ 1 2 3 ];
423 list_two = [ 4 5 6 ];
424 list_three = [ 7 8 9 ];
425 list_four = list_one.merge(list_two, list_three);
426 %]
427
428 The original lists are not modified.
429
430 slice(from, to)
431 Returns a slice of items in the list between the bounds passed as
432 arguments. If the second argument, 'to', isn't specified, then it
433 defaults to the last item in the list. The original list is not
434 modified.
435
436 [% first_three = list.slice(0,2) %]
437
438 [% last_three = list.slice(-3, -1) %]
439
440 splice(offset, length, list)
441 Behaves just like Perl's splice() function allowing you to selec‐
442 tively remove and/or replace elements in a list. It removes
443 'length' items from the list, starting at 'offset' and replaces
444 them with the items in 'list'.
445
446 [% play_game = [ 'play', 'scrabble' ];
447 ping_pong = [ 'ping', 'pong' ];
448 redundant = play_game.splice(1, 1, ping_pong);
449
450 redundant.join; # scrabble
451 play_game.join; # play ping pong
452 %]
453
454 The method returns a list of the items removed by the splice. You
455 can use the CALL directive to ignore the output if you're not plan‐
456 ning to do anything with it.
457
458 [% CALL play_game.splice(1, 1, ping_pong) %]
459
460 As well as providing a reference to a list of replacement values,
461 you can pass in a list of items.
462
463 [% CALL list.splice(-1, 0, 'foo', 'bar') %]
464
465 Be careful about passing just one item in as a replacement value.
466 If it is a reference to a list then the contents of the list will
467 be used. If it's not a list, then it will be treated as a single
468 value. You can use square brackets around a single item if you
469 need to be explicit:
470
471 [% # push a single item, an_item
472 CALL list.splice(-1, 0, an_item);
473
474 # push the items from another_list
475 CALL list.splice(-1, 0, another_list);
476
477 # push a reference to another_list
478 CALL list.splice(-1, 0, [ another_list ]);
479 %]
480
481 hash
482 Returns a reference to a hash array comprised of the elements in
483 the list. The even-numbered elements (0, 2, 4, etc) become the
484 keys and the odd-numbered elements (1, 3, 5, etc) the values.
485
486 [% list = ['pi', 3.14, 'e', 2.718] %]
487 [% hash = list.hash %]
488 [% hash.pi %] # 3.14
489 [% hash.e %] # 2.718
490
491 If a numerical argument is provided then the hash returned will
492 have keys generated for each item starting at the number specified.
493
494 [% list = ['beer', 'peanuts'] %]
495 [% hash = list.hash(1) %]
496 [% hash.1 %] # beer
497 [% hash.2 %] # peanuts
498
499 Automagic Promotion of Scalar to List for Virtual Methods
500
501 In addition to the scalar virtual methods listed in the previous sec‐
502 tion, you can also call any list virtual method against a scalar. The
503 item will be automagically promoted to a single element list and the
504 appropriate list virtual method will be called.
505
506 One particular benefit of this comes when calling subroutines or object
507 methods that return a list of items, rather than the preferred refer‐
508 ence to a list of items. In this case, the Template Toolkit automati‐
509 cally folds the items returned into a list.
510
511 The upshot is that you can continue to use existing Perl modules or
512 code that returns lists of items, without having to refactor it just to
513 keep the Template Toolkit happy (by returning references to list).
514 Class::DBI module is just one example of a particularly useful module
515 which returns values this way.
516
517 If only a single item is returned from a subroutine then the Template
518 Toolkit assumes it meant to return a single item (rather than a list of
519 1 item) and leaves it well alone, returning the single value as it is.
520 If you're executing a database query, for example, you might get 1 item
521 returned, or perhaps many items which are then folded into a list.
522
523 The FOREACH directive will happily accept either a list or a single
524 item which it will treat as a list. So it's safe to write directives
525 like this, where we assume that 'something' is bound to a subroutine
526 which might return 1 or more items:
527
528 [% FOREACH item IN something %]
529 ...
530 [% END %]
531
532 The automagic promotion of scalars to single item lists means that you
533 can also use list virtual methods safely, even if you only get one item
534 returned. For example:
535
536 [% something.first %]
537 [% something.join %]
538 [% something.reverse.join(', ') %]
539
540 Note that this is very much a last-ditch behaviour. If the single item
541 return is an object with a 'first' method, for example, then that will
542 be called, as expected, in preference to the list virtual method.
543
544 Defining Custom Virtual Methods
545
546 You can define your own virtual methods for scalars, lists and hash
547 arrays. The Template::Stash package variables $SCALAR_OPS, $LIST_OPS
548 and $HASH_OPS are references to hash arrays that define these virtual
549 methods. HASH_OPS and LIST_OPS methods are subroutines that accept a
550 hash/list reference as the first item. SCALAR_OPS are subroutines that
551 accept a scalar value as the first item. Any other arguments specified
552 when the method is called will be passed to the subroutine.
553
554 # load Template::Stash to make method tables visible
555 use Template::Stash;
556
557 # define list method to return new list of odd numbers only
558 $Template::Stash::LIST_OPS->{ odd } = sub {
559 my $list = shift;
560 return [ grep { $_ % 2 } @$list ];
561 };
562
563 template:
564
565 [% primes = [ 2, 3, 5, 7, 9 ] %]
566 [% primes.odd.join(', ') %] # 3, 5, 7, 9
567
569 Andy Wardley <abw@wardley.org>
570
571 <http://wardley.org/⎪http://wardley.org/>
572
574 Template Toolkit version 2.18, released on 09 February 2007.
575
577 Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
578
579 This module is free software; you can redistribute it and/or modify it
580 under the same terms as Perl itself.
581
582
583
584perl v5.8.8 2007-02-09 Template::Manual::VMethods(3)