1Template::Alloy::VMethoUds(e3r)Contributed Perl DocumentTaetmipolnate::Alloy::VMethod(3)
2
3
4

NAME

6       Template::Alloy::VMethod - VMethod role.
7

DESCRIPTION

9       The Template::Alloy::VMethod role provides all of the extra vmethods,
10       filters, and virtual objects that add to the base feature set of
11       Template::Alloy.  Most of the vmethods listed here are similar to those
12       provided by Template::Toolkit.  We will try to keep Template::Alloy's
13       in sync.  Template::Alloy also provides several extra methods that are
14       needed for HTML::Template::Expr support.
15

ROLE METHODS

17       define_vmethod
18           Defines a vmethod.  See Template::Alloy for more details.
19
20       "vmethod_*"
21           Methods by these names implement virtual methods that are more
22           complex than oneliners.  These methods are not exposed via the
23           role.
24
25       "filter_*"
26           Methods by these names implement filters that are more complex than
27           one liners.  These methods are not exposed via the role.
28

VIRTUAL METHOD LIST

30       The following is the list of builtin virtual methods and filters that
31       can be called on each type of data.
32
33       In Template::Alloy, the "|" operator can be used to call virtual
34       methods just the same way that the "." operator can.  The main
35       difference between the two is that on access to hashrefs or objects,
36       the "|" means to always call the virtual method or filter rather than
37       looking in the hashref for a key by that name, or trying to call that
38       method on the object.  This is similar to how TT3 will function.
39
40       Virtual methods are also made available via Virtual Objects which are
41       discussed in a later section.
42
43   SCALAR VIRTUAL METHODS AND FILTERS
44       The following is the list of builtin virtual methods and filters that
45       can be called on scalar data types.  In Alloy and TT3, filters and
46       virtual methods are more closely related than in TT2.  In general
47       anywhere a virtual method can be used a filter can be used also - and
48       likewise all scalar virtual methods can be used as filters.
49
50       In addition to the filters listed below, Alloy will automatically load
51       Template::Filters and use them if Template::Toolkit is installed.
52
53       In addition to the scalar virtual methods, any scalar will be
54       automatically converted to a single item list if a list virtual method
55       is called on it.
56
57       Scalar virtual methods are also available through the "Text" virtual
58       object (except for true filters such as eval and redirect).
59
60       All scalar virtual methods are available as top level functions as
61       well.  This is not true of TT2.  In Template::Alloy the following are
62       equivalent:
63
64           [% "abc".length %]
65           [% length("abc") %]
66
67       You may set VMETHOD_FUNCTIONS to 0 to disable this behavior.
68
69       '0'
70               [% item = 'foo' %][% item.0 %] Returns foo.
71
72           Allows for scalars to mask as arrays (scalars already will, but
73           this allows for more direct access).
74
75           Not available in TT.
76
77       abs
78               [% -1.abs %] Returns the absolute value
79
80       atan2
81               [% pi = 4 * 1.atan2(1) %]
82
83           Returns the arctangent.  The item itself represents Y, the passed
84           argument represents X.
85
86           Not available in TT - available in HTML::Template::Expr.
87
88       chunk
89               [% item.chunk(60).join("\n") %] Split string up into a list of chunks of text 60 chars wide.
90
91       collapse
92               [% item.collapse %] Strip leading and trailing whitespace and collapse all other space to one space.
93
94       cos
95               [% item.cos %] Returns the cosine of the item.
96
97           Not available in TT - available in HTML::Template::Expr.
98
99       defined
100               [% item.defined %] Always true - because the undef sub translates all undefs to ''.
101
102       eval
103               [% item.eval %]
104
105           Process the string as though it was a template.  This will start
106           the parsing engine and will use the same configuration as the
107           current process.  Alloy is several times faster at doing this than
108           TT is and is considered acceptable.
109
110           This is a filter and is not available via the Text virtual object.
111
112           Template::Alloy has attempted to make the compile process painless
113           and fast.  By default an MD5 sum of evaled is taken and used to
114           cache the AST.  This behavior can be disabled using the
115           CACHE_STR_REFS configuration item.
116
117           Template::Alloy also allows for named parameters to be passed to
118           the eval filter.
119
120               [% '[% 1 + 2 %]'.eval %]
121
122               [% '${ 1 + 2 }'.eval(interpolate => 1) %]
123
124               [% "#get( 1 + 2)"|eval(syntax => 'velocity') %]
125
126               [% '<TMPL_VAR EXPR="1 + 2">'.eval(syntax => 'hte') %]
127
128               [% '<TMPL_VAR EXPR="1 + 2">'.eval(syntax => 'hte') %]
129
130       evaltt
131               Same as the eval filter.
132
133       exp
134               [% 1.exp %] Something like 2.71828182845905
135
136           Returns "e" to the power of the item.
137
138       file
139               Same as the redirect filter.
140
141       fmt
142               [% item.fmt('%d') %]
143               [% item.fmt('%6s') %]
144               [% item.fmt('%*s', 6) %]
145
146           Similar to format.  Returns a string formatted with the passed
147           pattern.  Default pattern is %s.  Opposite from of the sprintf
148           vmethod.
149
150       format
151               [% item.format('%d') %]
152               [% item.format('%6s') %]
153               [% item.format('%*s', 6) %]
154
155           Print the string out in the specified format.  It is similar to the
156           "fmt" virtual method, except that the item is split on newline and
157           each line is processed separately.
158
159       hash
160               [% item.hash %] Returns a one item hash with a key of "value" and a value of the item.
161
162       hex
163               [% "FF".hex %]
164
165           Returns the decimal value of the passed hex numbers.  Note that you
166           may also just use [% 0xFF %].
167
168           Not available in TT - available in HTML::Template::Expr.
169
170       html
171               [% item.html %] Performs a very basic html encoding (swaps out &, <, > and " with the corresponding html entities)
172               Previously it also encoded the ' but this behavior did not match TT2's behavior.  Use .xml to obtain that behavior.
173
174       indent
175               [% item.indent(3) %] Indent by that number of spaces if an integer is passed (default is 4).
176
177               [% item.indent("Foo: ") %] Add the string "Foo: " to the beginning of every line.
178
179       int
180               [% item.int %] Return the integer portion of the value (0 if none).
181
182       json
183               [% item.json    %] Returns a JSON encoded representation.
184               [% item.json(1) %] Returns a pretty JSON encoded representation.
185
186       lc  Same as the lower vmethod.  Returns the lowercased version of the
187           item.
188
189       lcfirst
190               [% item.lcfirst %] Lowercase the leading letter.
191
192       length
193               [% item.length %] Return the length of the string.
194
195       list
196               [% item.list %] Returns a list (arrayref) with a single value of the item.
197
198       log
199               [% 8.exp.log %] Equal to 8.
200
201           Returns the natural log base "e" of the item.
202
203           Not available in TT - available in HTML::Template::Expr.
204
205       lower
206               [% item.lower %] Return the string lowercased.
207
208       match
209               [% item.match("(\w+) (\w+)") %] Return a list of items matching the pattern.
210
211               [% item.match("(\w+) (\w+)", 1) %] Same as before - but match globally.
212
213           In Template::Alloy and TT3 you can use regular expressions notation
214           as well.
215
216               [% item.match( /(\w+) (\w+)/ ) %] Same as before.
217
218               [% item.match( m{(\w+) (\w+)} ) %] Same as before.
219
220           Note that you can't use the 'g' regex modifier - you must pass the
221           second argument to turn on global match.
222
223       none
224           Returns the item without modification.  This was added as a
225           compliment case when the AUTO_FILTER configuration is specified.
226           Note that it must be called as a filter to bypass the application
227           of the AUTO_FILTER.
228
229               [% item | none %] Returns the item without modification.
230
231       null
232               [% item.null %] Return nothing.
233
234           If the item contains a coderef it will still be executed, but the
235           result would be ignored.
236
237       oct
238               [% "377".oct %]
239
240           Returns the decimal value of the octal string.  On recent versions
241           of perl you may also pass numbers starting with 0x which will be
242           interpreted as hexadecimal, and starting with 0b which will be
243           interpreted as binary.
244
245           Not available in TT - available in HTML::Template::Expr.
246
247       rand
248               [% item = 10; item.rand %] Returns a number greater or equal to 0 but less than 10.
249               [% 1.rand %]
250
251           Note: This filter is not available as of TT2.15.
252
253       remove
254               [% item.remove("\s+") %] Same as replace - but is global and replaces with nothing.
255
256       redirect
257               [% item.redirect("output_file.html") %]
258
259           Writes the contents out to the specified file.  The filename must
260           be relative to the OUTPUT_PATH configuration variable and the
261           OUTPUT_PATH variable must be set.
262
263           This is a filter and is not available via the Text virtual object.
264
265       repeat
266               [% item.repeat(3) %] Repeat the item 3 times
267
268               [% item.repeat(3, ' | ') %] Repeat the item 3 times separated with ' | '
269
270       replace
271               [% item.replace("\s+", "&nbsp;") %] Globally replace all space with &nbsp;
272
273               [% item.replace("foo", "bar", 0) %] Replace only the first instance of foo with bar.
274
275               [% item.replace("(\w+)", "($1)") %] Surround all words with parenthesis.
276
277           In Template::Alloy and TT3 you may also use normal regular
278           expression notation.
279
280               [% item.replace(/(\w+)/, "($1)") %] Same as before.
281
282           Note that you can't use the 'g' regex modifier - global match is on
283           by default.  You must pass the third argument of false to turn off
284           global match.
285
286       return
287           Returns the item from the inner most block, macro, or file.
288           Similar to the RETURN directive.
289
290               [% item.return %]
291               [% RETURN item %]
292
293       search
294               [% item.search("(\w+)") %] Tests if the given pattern is in the string.
295
296           In Template::Alloy and TT3 you may also use normal regular
297           expression notation.
298
299               [% item.search(/(\w+)/) %] Same as before.
300
301       sin
302               [% item.sin %] Returns the sine of the item.
303
304       size
305               [% item.size %] Always returns 1.
306
307       split
308               [% item.split %] Returns an arrayref from the item split on " "
309
310               [% item.split("\s+") %] Returns an arrayref from the item split on /\s+/
311
312               [% item.split("\s+", 3) %] Returns an arrayref from the item split on /\s+/ splitting until 3 elements are found.
313
314           In Template::Alloy and TT3 you may also use normal regular
315           expression notation.
316
317               [% item.split( /\s+/, 3 ) %] Same as before.
318
319       sprintf
320               [% item = "%d %d" %]
321               [% item.sprintf(7, 8) %]
322
323           Uses the pattern stored in self, and passes it to sprintf with the
324           passed arguments.  Opposite from the fmt vmethod.
325
326       sqrt
327               [% item.sqrt %]
328
329           Returns the square root of the number.
330
331       srand
332           Calls the perl srand function to set the internal random seed.
333           This will affect future calls to the rand vmethod.
334
335       stderr
336               [% item.stderr %] Print the item to the current STDERR handle.
337
338       substr
339               [% item.substr(i) %] Returns a substring of item starting at i and going to the end of the string.
340
341               [% item.substr(i, n) %] Returns a substring of item starting at i and going n characters.
342
343       trim
344               [% item.trim %] Strips leading and trailing whitespace.
345
346       uc  Same as the upper command.  Returns uppercased string.
347
348       ucfirst
349               [% item.ucfirst %] Uppercase the leading letter.
350
351       upper
352               [% item.upper %] Return the string uppercased.
353
354       uri
355               [% item.uri %] Perform a very basic URI encoding.
356
357       url
358               [% item.url %] Perform a URI encoding - but some characters such
359                              as : and / are left intact.
360
361       xml
362               [% item.xml %] Performs a very basic xml encoding (swaps out &, <, >, ' and " with the corresponding xml entities)
363
364   LIST VIRTUAL METHODS
365       The following methods can be called on an arrayref type data structures
366       (scalar types will automatically promote to a single element list and
367       call these methods if needed):
368
369       Additionally, list virtual methods can be accessed via the List Virtual
370       Object.
371
372       fmt
373               [% mylist.fmt('%s', ', ') %]
374               [% mylist.fmt('%6s', ', ') %]
375               [% mylist.fmt('%*s', ', ', 6) %]
376
377           Passed a pattern and an string to join on.  Returns a string of the
378           values of the list formatted with the passed pattern and joined
379           with the passed string.  Default pattern is %s and the default join
380           string is a space.
381
382       first
383               [% mylist.first(3) %]  Returns a list of the first 3 items in the list.
384
385       grep
386               [% mylist.grep("^\w+\.\w+$") %] Returns a list of all items matching the pattern.
387
388           In Template::Alloy and TT3 you may also use normal regular
389           expression notation.
390
391               [% mylist.grep(/^\w+\.\w+$/) %] Same as before.
392
393               [% mylist.grep(->(a){ a.foo.bar }
394
395       hash
396               [% mylist.hash %] Returns a hashref with the array indexes as keys and the values as values.
397
398       join
399               [% mylist.join %] Joins on space.
400               [% mylist.join(", ") Joins on the passed argument.
401
402       json
403               [% mylist.json    %] Returns a JSON encoded representation.
404               [% mylist.json(1) %] Returns a pretty JSON encoded representation.
405
406       last
407               [% mylist.last(3) %]  Returns a list of the last 3 items in the list.
408
409       list
410               [% mylist.list %] Returns a reference to the list.
411
412       map (Not in TT2)
413               [% mylist.map(->{ this.upper }) %] Returns a list with the macro played on each item.
414               [% mylist.map(->(a){ a.upper }) %] Same thing
415
416           The RETURN directive or return list, item, and hash vmethods allow
417           for returning more interesting items.
418
419               [% [1..3].map(->(a){ [1..a].return }) %]
420
421       max
422               [% mylist.max %] Returns the last item in the array.
423
424       merge
425               [% mylist.merge(list2) %] Returns a new list with all defined items from list2 added.
426
427       nsort
428               [% mylist.nsort %] Returns the numerically sorted items of the list.  If the items are
429               hashrefs, a key containing the field to sort on can be passed.
430
431       pop
432               [% mylist.pop %] Removes and returns the last element from the arrayref (the stash is modified).
433
434       push
435               [% mylist.push(23) %] Adds an element to the end of the arrayref (the stash is modified).
436
437       pick
438               [% mylist.pick %] Returns a random item from the list.
439               [% ['a' .. 'z'].pick %]
440
441           An additional numeric argument is how many items to return.
442
443               [% ['a' .. 'z'].pick(8).join('') %]
444
445           Note: This filter is not available as of TT2.15.
446
447       return
448           Returns the list from the inner most block, macro, or file.
449           Similar to the RETURN directive.
450
451               [% mylist.return %]
452               [% RETURN mylist %]
453
454       reverse
455               [% mylist.reverse %] Returns the list in reverse order.
456
457       shift
458               [% mylist.shift %] Removes and returns the first element of the arrayref (the stash is modified).
459
460       size
461               [% mylist.size %] Returns the number of elements in the array.
462
463       slice
464               [% mylist.slice(i, n) %] Returns a list from the arrayref beginning at index i and continuing for n items.
465
466       sort
467               [% mylist.sort %] Returns the alphabetically sorted items of the list.  If the items are
468               hashrefs, a key containing the field to sort on can be passed.
469
470       splice
471               [% mylist.splice(i, n) %] Removes items from array beginning at i and continuing for n items.
472
473               [% mylist.splice(i, n, list2) %] Same as before, but replaces removed items with the items
474               from list2.
475
476       unique
477               [% mylist.unique %] Return a list of the unique items in the array.
478
479       unshift
480               [% mylist.unshift(23) %] Adds an item to the beginning of the arrayref.
481
482   HASH VIRTUAL METHODS
483       The following methods can be called on hash type data structures:
484
485       Additionally, list virtual methods can be accessed via the Hash Virtual
486       Object.
487
488       fmt
489               [% myhash.fmt('%s => %s', "\n") %]
490               [% myhash.fmt('%4s => %5s', "\n") %]
491               [% myhash.fmt('%*s => %*s', "\n", 4, 5) %]
492
493           Passed a pattern and an string to join on.  Returns a string of the
494           key/value pairs of the hash formatted with the passed pattern and
495           joined with the passed string.  Default pattern is "%s\t%s" and the
496           default join string is a newline.
497
498       defined
499               [% myhash.defined('a') %]  Checks if a is defined in the hash.
500
501       delete
502               [% myhash.delete('a') %]  Deletes the item from the hash.
503
504           Unlink Perl the value is not returned.  Multiple values may be
505           passed and represent the keys to be deleted.
506
507       each
508               [% myhash.each.join(", ") %]  Turns the contents of the hash into a list - subject
509               to change as TT is changing the operations of each and list.
510
511       exists
512               [% myhash.exists('a') %]  Checks if a is in the hash.
513
514       hash
515               [% myhash.hash %]  Returns a reference to the hash.
516
517       import
518               [% myhash.import(hash2) %]  Overlays the keys of hash2 over the keys of myhash.
519
520       item
521               [% myhash.item(key) %] Returns the hashes value for that key.
522
523       items
524               [% myhash.items %] Returns a list of the key and values (flattened hash)
525
526       json
527               [% myhash.json    %] Returns a JSON encoded representation.
528               [% myhash.json(1) %] Returns a pretty JSON encoded representation.
529
530       keys
531               [% myhash.keys.join(', ') %] Returns an arrayref of the keys of the hash.
532
533       list
534               [% myhash.list %] Returns an arrayref with the hash as a single value (subject to change).
535
536       pairs
537               [% myhash.pairs %] Returns an arrayref of hashrefs where each hash contains {key => $key, value => $value}
538               for each value of the hash.
539
540       nsort
541               [% myhash.nsort.join(", ") %] Returns a list of keys numerically sorted by the values.
542
543       return
544           Returns the hash from the inner most block, macro, or file.
545           Similar to the RETURN directive.
546
547               [% myhash.return %]
548               [% RETURN myhash %]
549
550       size
551               [% myhash.size %] Returns the number of key/value pairs in the hash.
552
553       sort
554               [% myhash.sort.join(", ") Returns a list of keys alphabetically sorted by the values.
555
556       values
557               [% myhash.values.join(', ') %] Returns an arrayref of the values of the hash.
558

VIRTUAL OBJECTS

560       TT3 has a concept of Text, List, and Hash virtual objects which provide
561       direct access to the scalar, list, and hash virtual methods.  In the
562       TT3 engine this will allow for more concise generated code.  Because
563       Alloy does not generated perl code to be executed later, Alloy provides
564       for these virtual objects but does so as more of a namespace (using the
565       methods does not provide a speed optimization in your template - just
566       may help clarify things).
567
568           [% a = "foo"; a.length %] => 3
569
570           [% a = "foo"; Text.length(a) %] => 3
571
572           [% a = Text.new("foo"); a.length %] => 3
573
574
575           [% a = [1 .. 30]; a.size %] => 30
576
577           [% a = [1 .. 30]; List.size(a) %] => 30
578
579           [% a = List.new(1 .. 30); a.size %] => 30
580
581
582           [% a = {a => 1, b => 2}; a.size %] => 2
583
584           [% a = {a => 1, b => 2}; Hash.size(a) %] => 2
585
586           [% a = Hash.new({a => 1, b => 2}); a.size %] => 2
587
588           [% a = Hash.new(a => 1, b => 2); a.size %] => 2
589
590           [% a = Hash.new(a = 1, b = 2); a.size %] => 2
591
592           [% a = Hash.new('a', 1, 'b', 2); a.size %] => 2
593
594       One limitation is that if you pass a key named "Text", "List", or
595       "Hash" in your variable stash - the corresponding virtual object will
596       be hidden.
597
598       Additionally, you can use all of the Virtual object methods with the
599       pipe operator.
600
601           [% {a => 1, b => 2}
602              | Hash.keys
603              | List.join(", ") %] => a, b
604
605       Again, there aren't any speed optimizations to using the virtual
606       objects in Alloy, but it can help clarify the intent in some cases.
607
608       Note: these aren't really objects.  All of the "virtual objects" are
609       references to the $SCALAR_OPS, $LIST_OPS, and $HASH_OPS hashes found in
610       the $VOBJS hash of Template::Alloy.
611

AUTHOR

613       Paul Seamons <paul@seamons.com>
614

LICENSE

616       This module may be distributed under the same terms as Perl itself.
617
618
619
620perl v5.36.0                      2023-01-20       Template::Alloy::VMethod(3)
Impressum