1Template::Filters(3)  User Contributed Perl Documentation Template::Filters(3)
2
3
4

NAME

6       Template::Filters - Post-processing filters for template blocks
7

SYNOPSIS

9           use Template::Filters;
10
11           $filters = Template::Filters->new(\%config);
12
13           ($filter, $error) = $filters->fetch($name, \@args, $context);
14

DESCRIPTION

16       The Template::Filters module implements a provider for creating and/or
17       returning subroutines that implement the standard filters.  Additional
18       custom filters may be provided via the FILTERS options.
19

METHODS

21       new(\%params)
22
23       Constructor method which instantiates and returns a reference to a Tem‐
24       plate::Filters object.  A reference to a hash array of configuration
25       items may be passed as a parameter.  These are described below.
26
27           my $filters = Template::Filters->new({
28               FILTERS => { ... },
29           });
30
31           my $template = Template->new({
32               LOAD_FILTERS => [ $filters ],
33           });
34
35       A default Template::Filters module is created by the Template.pm module
36       if the LOAD_FILTERS option isn't specified.  All configuration parame‐
37       ters are forwarded to the constructor.
38
39           $template = Template->new({
40               FILTERS => { ... },
41           });
42
43       fetch($name, \@args, $context)
44
45       Called to request that a filter of a given name be provided.  The name
46       of the filter should be specified as the first parameter.  This should
47       be one of the standard filters or one specified in the FILTERS configu‐
48       ration hash.  The second argument should be a reference to an array
49       containing configuration parameters for the filter.  This may be speci‐
50       fied as 0, or undef where no parameters are provided.  The third argu‐
51       ment should be a reference to the current Template::Context object.
52
53       The method returns a reference to a filter sub-routine on success.  It
54       may also return (undef, STATUS_DECLINE) to decline the request, to
55       allow delegation onto other filter providers in the LOAD_FILTERS chain
56       of responsibility.  On error, ($error, STATUS_ERROR) is returned where
57       $error is an error message or Template::Exception object indicating the
58       error that occurred.
59
60       When the TOLERANT option is set, errors are automatically downgraded to
61       a STATUS_DECLINE response.
62

CONFIGURATION OPTIONS

64       The following list details the configuration options that can be pro‐
65       vided to the Template::Filters new() constructor.
66
67       FILTERS
68           The FILTERS option can be used to specify custom filters which can
69           then be used with the FILTER directive like any other.  These are
70           added to the standard filters which are available by default.  Fil‐
71           ters specified via this option will mask any standard filters of
72           the same name.
73
74           The FILTERS option should be specified as a reference to a hash
75           array in which each key represents the name of a filter.  The cor‐
76           responding value should contain a reference to an array containing
77           a subroutine reference and a flag which indicates if the filter is
78           static (0) or dynamic (1).  A filter may also be specified as a
79           solitary subroutine reference and is assumed to be static.
80
81               $filters = Template::Filters->new({
82                   FILTERS => {
83                       'sfilt1' =>   \&static_filter,      # static
84                       'sfilt2' => [ \&static_filter, 0 ], # same as above
85                       'dfilt1' => [ \&dyanamic_filter_factory, 1 ],
86                   },
87               });
88
89           Additional filters can be specified at any time by calling the
90           define_filter() method on the current Template::Context object.
91           The method accepts a filter name, a reference to a filter subrou‐
92           tine and an optional flag to indicate if the filter is dynamic.
93
94               my $context = $template->context();
95               $context->define_filter('new_html', \&new_html);
96               $context->define_filter('new_repeat', \&new_repeat, 1);
97
98           Static filters are those where a single subroutine reference is
99           used for all invocations of a particular filter.  Filters that
100           don't accept any configuration parameters (e.g. 'html') can be
101           implemented statically.  The subroutine reference is simply
102           returned when that particular filter is requested.  The subroutine
103           is called to filter the output of a template block which is passed
104           as the only argument.  The subroutine should return the modified
105           text.
106
107               sub static_filter {
108                   my $text = shift;
109                   # do something to modify $text...
110                   return $text;
111               }
112
113           The following template fragment:
114
115               [% FILTER sfilt1 %]
116               Blah blah blah.
117               [% END %]
118
119           is approximately equivalent to:
120
121               &static_filter("\nBlah blah blah.\n");
122
123           Filters that can accept parameters (e.g. 'truncate') should be
124           implemented dynamically.  In this case, the subroutine is taken to
125           be a filter 'factory' that is called to create a unique filter sub‐
126           routine each time one is requested.  A reference to the current
127           Template::Context object is passed as the first parameter, followed
128           by any additional parameters specified.  The subroutine should
129           return another subroutine reference (usually a closure) which
130           implements the filter.
131
132               sub dynamic_filter_factory {
133                   my ($context, @args) = @_;
134
135                   return sub {
136                       my $text = shift;
137                       # do something to modify $text...
138                       return $text;
139                   }
140               }
141
142           The following template fragment:
143
144               [% FILTER dfilt1(123, 456) %]
145               Blah blah blah
146               [% END %]
147
148           is approximately equivalent to:
149
150               my $filter = &dynamic_filter_factory($context, 123, 456);
151               &$filter("\nBlah blah blah.\n");
152
153           See the FILTER directive for further examples.
154
155       TOLERANT
156           The TOLERANT flag is used by the various Template Toolkit provider
157           modules (Template::Provider, Template::Plugins, Template::Filters)
158           to control their behaviour when errors are encountered.  By
159           default, any errors are reported as such, with the request for the
160           particular resource (template, plugin, filter) being denied and an
161           exception raised.  When the TOLERANT flag is set to any true val‐
162           ues, errors will be silently ignored and the provider will instead
163           return STATUS_DECLINED.  This allows a subsequent provider to take
164           responsibility for providing the resource, rather than failing the
165           request outright.  If all providers decline to service the request,
166           either through tolerated failure or a genuine disinclination to
167           comply, then a '<resource> not found' exception is raised.
168
169       DEBUG
170           The DEBUG option can be used to enable debugging messages from the
171           Template::Filters module by setting it to include the DEBUG_FILTERS
172           value.
173
174               use Template::Constants qw( :debug );
175
176               my $template = Template->new({
177                   DEBUG => DEBUG_FILTERS ⎪ DEBUG_PLUGINS,
178               });
179

TEMPLATE TOOLKIT FILTERS

181       The following standard filters are distributed with the Template Tool‐
182       kit.
183
184       format(format)
185
186       The 'format' filter takes a format string as a parameter (as per
187       printf()) and formats each line of text accordingly.
188
189           [% FILTER format('<!-- %-40s -->') %]
190           This is a block of text filtered
191           through the above format.
192           [% END %]
193
194       output:
195
196           <!-- This is a block of text filtered        -->
197           <!-- through the above format.               -->
198
199       upper
200
201       Folds the input to UPPER CASE.
202
203           [% "hello world" FILTER upper %]
204
205       output:
206
207           HELLO WORLD
208
209       lower
210
211       Folds the input to lower case.
212
213           [% "Hello World" FILTER lower %]
214
215       output:
216
217           hello world
218
219       ucfirst
220
221       Folds the first character of the input to UPPER CASE.
222
223           [% "hello" FILTER ucfirst %]
224
225       output:
226
227           Hello
228
229       lcfirst
230
231       Folds the first character of the input to lower case.
232
233           [% "HELLO" FILTER lcfirst %]
234
235       output:
236
237           hELLO
238
239       trim
240
241       Trims any leading or trailing whitespace from the input text.  Particu‐
242       larly useful in conjunction with INCLUDE, PROCESS, etc., having the
243       same effect as the TRIM configuration option.
244
245           [% INCLUDE myfile ⎪ trim %]
246
247       collapse
248
249       Collapse any whitespace sequences in the input text into a single
250       space.  Leading and trailing whitespace (which would be reduced to a
251       single space) is removed, as per trim.
252
253           [% FILTER collapse %]
254
255              The   cat
256
257              sat    on
258
259              the   mat
260
261           [% END %]
262
263       output:
264
265           The cat sat on the mat
266
267       html
268
269       Converts the characters '<', '>', '&' and '"' to '&lt;', '&gt;',
270       '&amp;', and '&quot;' respectively, protecting them from being inter‐
271       preted as representing HTML tags or entities.
272
273           [% FILTER html %]
274           Binary "<=>" returns -1, 0, or 1 depending on...
275           [% END %]
276
277       output:
278
279           Binary "&lt;=&gt;" returns -1, 0, or 1 depending on...
280
281       html_entity
282
283       The html filter is fast and simple but it doesn't encode the full range
284       of HTML entities that your text may contain.  The html_entity filter
285       uses either the Apache::Util module (which is written in C and is
286       therefore faster) or the HTML::Entities module (written in Perl but
287       equally as comprehensive) to perform the encoding.  If one or other of
288       these modules are installed on your system then the text will be
289       encoded (via the escape_html() or encode_entities() subroutines respec‐
290       tively) to convert all extended characters into their appropriate HTML
291       entities (e.g. converting 'é' to '&eacute;').  If neither module is
292       available on your system then an 'html_entity' exception will be thrown
293       reporting an appropriate message.
294
295       For further information on HTML entity encoding, see
296       http://www.w3.org/TR/REC-html40/sgml/entities.html.
297
298       html_para
299
300       This filter formats a block of text into HTML paragraphs.  A sequence
301       of two or more newlines is used as the delimiter for paragraphs which
302       are then wrapped in HTML <p>...</p> tags.
303
304           [% FILTER html_para %]
305           The cat sat on the mat.
306
307           Mary had a little lamb.
308           [% END %]
309
310       output:
311
312           <p>
313           The cat sat on the mat.
314           </p>
315
316           <p>
317           Mary had a little lamb.
318           </p>
319
320       html_break / html_para_break
321
322       Similar to the html_para filter described above, but uses the HTML tag
323       sequence <br><br> to join paragraphs.
324
325           [% FILTER html_break %]
326           The cat sat on the mat.
327
328           Mary had a little lamb.
329           [% END %]
330
331       output:
332
333           The cat sat on the mat.
334           <br>
335           <br>
336           Mary had a little lamb.
337
338       html_line_break
339
340       This filter replaces any newlines with <br> HTML tags, thus preserving
341       the line breaks of the original text in the HTML output.
342
343           [% FILTER html_line_break %]
344           The cat sat on the mat.
345           Mary had a little lamb.
346           [% END %]
347
348       output:
349
350           The cat sat on the mat.<br>
351           Mary had a little lamb.<br>
352
353       uri
354
355       This filter URI escapes the input text, converting any characters out‐
356       side of the permitted URI character set (as defined by RFC 2396) into a
357       %nn hex escape.
358
359           [% 'my file.html' ⎪ uri %]
360
361       output:
362
363           my%20file.html
364
365       Note that as of TT version 2.16, the uri filter now correctly encodes
366       all reserved characters.  This includes "&", "@", "/", ";", ":", "=",
367       "+", "?" and "$" which were not escaped (incorrectly) by the uri filter
368       in versions 2.15 and earlier.  See RFC 2396 for further details.
369
370       indent(pad)
371
372       Indents the text block by a fixed pad string or width.  The 'pad' argu‐
373       ment can be specified as a string, or as a numerical value to indicate
374       a pad width (spaces).  Defaults to 4 spaces if unspecified.
375
376           [% FILTER indent('ME> ') %]
377           blah blah blah
378           cabbages, rhubard, onions
379           [% END %]
380
381       output:
382
383           ME> blah blah blah
384           ME> cabbages, rhubard, onions
385
386       truncate(length,dots)
387
388       Truncates the text block to the length specified, or a default length
389       of 32.  Truncated text will be terminated with '...' (i.e. the '...'
390       falls inside the required length, rather than appending to it).
391
392           [% FILTER truncate(21) %]
393           I have much to say on this matter that has previously
394           been said on more than one occasion.
395           [% END %]
396
397       output:
398
399           I have much to say...
400
401       If you want to use something other than '...' you can pass that as a
402       second argument.
403
404           [% FILTER truncate(26, '&hellip;') %]
405           I have much to say on this matter that has previously
406           been said on more than one occasion.
407           [% END %]
408
409       output:
410
411           I have much to say&hellip;
412
413       repeat(iterations)
414
415       Repeats the text block for as many iterations as are specified
416       (default: 1).
417
418           [% FILTER repeat(3) %]
419           We want more beer and we want more beer,
420           [% END %]
421           We are the more beer wanters!
422
423       output:
424
425           We want more beer and we want more beer,
426           We want more beer and we want more beer,
427           We want more beer and we want more beer,
428           We are the more beer wanters!
429
430       remove(string)
431
432       Searches the input text for any occurrences of the specified string and
433       removes them.  A Perl regular expression may be specified as the search
434       string.
435
436           [% "The  cat  sat  on  the  mat" FILTER remove('\s+') %]
437
438       output:
439
440           Thecatsatonthemat
441
442       replace(search, replace)
443
444       Similar to the remove filter described above, but taking a second
445       parameter which is used as a replacement string for instances of the
446       search string.
447
448           [% "The  cat  sat  on  the  mat" ⎪ replace('\s+', '_') %]
449
450       output:
451
452           The_cat_sat_on_the_mat
453
454       redirect(file, options)
455
456       The 'redirect' filter redirects the output of the block into a separate
457       file, specified relative to the OUTPUT_PATH configuration item.
458
459           [% FOREACH user = myorg.userlist %]
460              [% FILTER redirect("users/${user.id}.html") %]
461                 [% INCLUDE userinfo %]
462              [% END %]
463           [% END %]
464
465       or more succinctly, using side-effect notation:
466
467           [% INCLUDE userinfo
468                FILTER redirect("users/${user.id}.html")
469                  FOREACH user = myorg.userlist
470           %]
471
472       A 'file' exception will be thrown if the OUTPUT_PATH option is unde‐
473       fined.
474
475       An optional 'binmode' argument can follow the filename to explicitly
476       set the output file to binary mode.
477
478           [% PROCESS my/png/generator
479                FILTER redirect("images/logo.png", binmode=1) %]
480
481       For backwards compatibility with earlier versions, a single true/false
482       value can be used to set binary mode.
483
484           [% PROCESS my/png/generator
485                FILTER redirect("images/logo.png", 1) %]
486
487       For the sake of future compatibility and clarity, if nothing else, we
488       would strongly recommend you explicitly use the named 'binmode' option
489       as shown in the first example.
490
491       eval / evaltt
492
493       The 'eval' filter evaluates the block as template text, processing any
494       directives embedded within it.  This allows template variables to con‐
495       tain template fragments, or for some method to be provided for return‐
496       ing template fragments from an external source such as a database,
497       which can then be processed in the template as required.
498
499           my $vars  = {
500               fragment => "The cat sat on the [% place %]",
501           };
502           $template->process($file, $vars);
503
504       The following example:
505
506           [% fragment ⎪ eval %]
507
508       is therefore equivalent to
509
510           The cat sat on the [% place %]
511
512       The 'evaltt' filter is provided as an alias for 'eval'.
513
514       perl / evalperl
515
516       The 'perl' filter evaluates the block as Perl code.  The EVAL_PERL
517       option must be set to a true value or a 'perl' exception will be
518       thrown.
519
520           [% my_perl_code ⎪ perl %]
521
522       In most cases, the [% PERL %] ... [% END %] block should suffice for
523       evaluating Perl code, given that template directives are processed
524       before being evaluate as Perl.  Thus, the previous example could have
525       been written in the more verbose form:
526
527           [% PERL %]
528           [% my_perl_code %]
529           [% END %]
530
531       as well as
532
533           [% FILTER perl %]
534           [% my_perl_code %]
535           [% END %]
536
537       The 'evalperl' filter is provided as an alias for 'perl' for backwards
538       compatibility.
539
540       stdout(options)
541
542       The stdout filter prints the output generated by the enclosing block to
543       STDOUT.  The 'binmode' option can be passed as either a named parameter
544       or a single argument to set STDOUT to binary mode (see the binmode perl
545       function).
546
547           [% PROCESS something/cool
548                  FILTER stdout(binmode=1) # recommended %]
549
550           [% PROCESS something/cool
551                  FILTER stdout(1)         # alternate %]
552
553       The stdout filter can be used to force binmode on STDOUT, or also
554       inside redirect, null or stderr blocks to make sure that particular
555       output goes to stdout. See the null filter below for an example.
556
557       stderr
558
559       The stderr filter prints the output generated by the enclosing block to
560       STDERR.
561
562       null
563
564       The null filter prints nothing.  This is useful for plugins whose meth‐
565       ods return values that you don't want to appear in the output.  Rather
566       than assigning every plugin method call to a dummy variable to silence
567       it, you can wrap the block in a null filter:
568
569           [% FILTER null;
570               USE im = GD.Image(100,100);
571               black = im.colorAllocate(0,   0, 0);
572               red   = im.colorAllocate(255,0,  0);
573               blue  = im.colorAllocate(0,  0,  255);
574               im.arc(50,50,95,75,0,360,blue);
575               im.fill(50,50,red);
576               im.png ⎪ stdout(1);
577              END;
578           -%]
579
580       Notice the use of the stdout filter to ensure that a particular expres‐
581       sion generates output to stdout (in this case in binary mode).
582
583       latex(outputType)
584
585       The latex() filter is no longer part of the core Template Toolkit dis‐
586       tribution as of version 2.15.  You can download it as a separate Tem‐
587       plate-Latex distribution from CPAN.
588

AUTHOR

590       Andy Wardley <abw@wardley.org>
591
592       <http://wardley.org/http://wardley.org/>
593

VERSION

595       2.85, distributed as part of the Template Toolkit version 2.18,
596       released on 09 February 2007.
597
599         Copyright (C) 1996-2007 Andy Wardley.  All Rights Reserved.
600
601       This module is free software; you can redistribute it and/or modify it
602       under the same terms as Perl itself.
603

SEE ALSO

605       Template, Template::Context, Template::Manual::Filters
606
607
608
609perl v5.8.8                       2007-02-09              Template::Filters(3)
Impressum