[%# # IMPORTANT NOTE # This documentation is generated automatically from source # templates. Any changes you make here may be lost. # # The 'docsrc' documentation source bundle is available for download # from http://www.template-toolkit.org/docs.html and contains all # the source templates, XML files, scripts, etc., from which the # documentation for the Template Toolkit is built. -%] [% META book = 'Modules' page = 'Filters' %] [% WRAPPER toc; PROCESS tocitem title ="SYNOPSIS" subs = []; PROCESS tocitem title ="DESCRIPTION" subs = []; PROCESS tocitem title ="METHODS" subs = [ "new(\\%params) ", "fetch(\$name, \\@args, \$context)" ]; PROCESS tocitem title ="CONFIGURATION OPTIONS" subs = []; PROCESS tocitem title ="TEMPLATE TOOLKIT FILTERS" subs = [ "format(format)", "upper", "lower", "ucfirst", "lcfirst", "trim", "collapse", "html", "html_entity", "html_para", "html_break / html_para_break", "html_line_break", "uri", "url", "indent(pad)", "truncate(length,dots)", "repeat(iterations)", "remove(string) ", "replace(search, replace) ", "redirect(file, options)", "eval / evaltt", "perl / evalperl", "stdout(options)", "stderr", "null", "latex(outputType)" ]; PROCESS tocitem title ="AUTHOR" subs = []; PROCESS tocitem title ="VERSION" subs = []; PROCESS tocitem title ="COPYRIGHT" subs = []; PROCESS tocitem title ="SEE ALSO" subs = []; END %] [% WRAPPER section title="SYNOPSIS" -%]
    use Template::Filters;
    $filters = Template::Filters->new(\%config);
    ($filter, $error) = $filters->fetch($name, \@args, $context);
[%- END %] [% WRAPPER section title="DESCRIPTION" -%]

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

[%- END %] [% WRAPPER section title="METHODS" -%][% WRAPPER subsection title = "new(\\%params) " -%]

Constructor method which instantiates and returns a reference to a Template::Filters object. A reference to a hash array of configuration items may be passed as a parameter. These are described below.

    my $filters = Template::Filters->new({
        FILTERS => { ... },
    });
    my $template = Template->new({
        LOAD_FILTERS => [ $filters ],
    });

A default Template::Filters module is created by the Template.pm module if the LOAD_FILTERS option isn't specified. All configuration parameters are forwarded to the constructor.

    $template = Template->new({
        FILTERS => { ... },
    });
[%- END %] [% WRAPPER subsection title = "fetch(\$name, \\@args, \$context)" -%]

Called to request that a filter of a given name be provided. The name of the filter should be specified as the first parameter. This should be one of the standard filters or one specified in the FILTERS configuration hash. The second argument should be a reference to an array containing configuration parameters for the filter. This may be specified as 0, or undef where no parameters are provided. The third argument should be a reference to the current Template::Context object.

The method returns a reference to a filter sub-routine on success. It may also return (undef, STATUS_DECLINE) to decline the request, to allow delegation onto other filter providers in the LOAD_FILTERS chain of responsibility. On error, ($error, STATUS_ERROR) is returned where $error is an error message or Template::Exception object indicating the error that occurred.

When the TOLERANT option is set, errors are automatically downgraded to a STATUS_DECLINE response.

[%- END %] [%- END %] [% WRAPPER section title="CONFIGURATION OPTIONS" -%]

The following list details the configuration options that can be provided to the Template::Filters new() constructor.

[%- END %] [% WRAPPER section title="TEMPLATE TOOLKIT FILTERS" -%]

The following standard filters are distributed with the Template Toolkit.

[% WRAPPER subsection title = "format(format)" -%]

The 'format' filter takes a format string as a parameter (as per printf()) and formats each line of text accordingly.

    [% tt_start_tag %] FILTER format('<!-- %-40s -->') [% tt_end_tag %]
    This is a block of text filtered 
    through the above format.
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    <!-- This is a block of text filtered        -->
    <!-- through the above format.               -->
[%- END %] [% WRAPPER subsection title = "upper" -%]

Folds the input to UPPER CASE.

    [% tt_start_tag %] "hello world" FILTER upper [% tt_end_tag %]

output:

    HELLO WORLD
[%- END %] [% WRAPPER subsection title = "lower" -%]

Folds the input to lower case.

    [% tt_start_tag %] "Hello World" FILTER lower [% tt_end_tag %]

output:

    hello world
[%- END %] [% WRAPPER subsection title = "ucfirst" -%]

Folds the first character of the input to UPPER CASE.

    [% tt_start_tag %] "hello" FILTER ucfirst [% tt_end_tag %]

output:

    Hello
[%- END %] [% WRAPPER subsection title = "lcfirst" -%]

Folds the first character of the input to lower case.

    [% tt_start_tag %] "HELLO" FILTER lcfirst [% tt_end_tag %]

output:

    hELLO
[%- END %] [% WRAPPER subsection title = "trim" -%]

Trims any leading or trailing whitespace from the input text. Particularly useful in conjunction with INCLUDE, PROCESS, etc., having the same effect as the TRIM configuration option.

    [% tt_start_tag %] INCLUDE myfile | trim [% tt_end_tag %]
[%- END %] [% WRAPPER subsection title = "collapse" -%]

Collapse any whitespace sequences in the input text into a single space. Leading and trailing whitespace (which would be reduced to a single space) is removed, as per trim.

    [% tt_start_tag %] FILTER collapse [% tt_end_tag %]
       The   cat
       sat    on
       the   mat
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    The cat sat on the mat
[%- END %] [% WRAPPER subsection title = "html" -%]

Converts the characters '<', '>', '&' and '"' to '&lt;', '&gt;', '&amp;', and '&quot;' respectively, protecting them from being interpreted as representing HTML tags or entities.

    [% tt_start_tag %] FILTER html [% tt_end_tag %]
    Binary "<=>" returns -1, 0, or 1 depending on...
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    Binary "&lt;=&gt;" returns -1, 0, or 1 depending on...
[%- END %] [% WRAPPER subsection title = "html_entity" -%]

The html filter is fast and simple but it doesn't encode the full range of HTML entities that your text may contain. The html_entity filter uses either the Apache::Util module (which is written in C and is therefore faster) or the HTML::Entities module (written in Perl but equally as comprehensive) to perform the encoding. If one or other of these modules are installed on your system then the text will be encoded (via the escape_html() or encode_entities() subroutines respectively) to convert all extended characters into their appropriate HTML entities (e.g. converting '' to '&eacute;'). If neither module is available on your system then an 'html_entity' exception will be thrown reporting an appropriate message.

For further information on HTML entity encoding, see http://www.w3.org/TR/REC-html40/sgml/entities.html.

[%- END %] [% WRAPPER subsection title = "html_para" -%]

This filter formats a block of text into HTML paragraphs. A sequence of two or more newlines is used as the delimiter for paragraphs which are then wrapped in HTML <p>...</p> tags.

    [% tt_start_tag %] FILTER html_para [% tt_end_tag %]
    The cat sat on the mat.
    Mary had a little lamb.
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    <p>
    The cat sat on the mat.
    </p>
    <p>
    Mary had a little lamb.
    </p>
[%- END %] [% WRAPPER subsection title = "html_break / html_para_break" -%]

Similar to the html_para filter described above, but uses the HTML tag sequence <br><br> to join paragraphs.

    [% tt_start_tag %] FILTER html_break [% tt_end_tag %]
    The cat sat on the mat.
    Mary had a little lamb.
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    The cat sat on the mat.
    <br>
    <br>
    Mary had a little lamb.
[%- END %] [% WRAPPER subsection title = "html_line_break" -%]

This filter replaces any newlines with <br> HTML tags, thus preserving the line breaks of the original text in the HTML output.

    [% tt_start_tag %] FILTER html_line_break [% tt_end_tag %]
    The cat sat on the mat.
    Mary had a little lamb.
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    The cat sat on the mat.<br>
    Mary had a little lamb.<br>
[%- END %] [% WRAPPER subsection title = "uri" -%]

This filter URI escapes the input text, converting any characters outside of the permitted URI character set (as defined by RFC 2396) into a '%nn' hex escape.

    [% tt_start_tag %] 'my file.html' | uri [% tt_end_tag %]

output:

    my%20file.html

The uri filter correctly encodes all reserved characters, including '&', '@', '/', ';', ':', '=', '+', '?' and '$'. This filter is typically used to encode parameters in a URL that could otherwise be interpreted as part of the URL. Here's an example:

    [% tt_start_tag %] path  = 'http://tt2.org/example'
       back  = '/other?foo=bar&baz=bam' 
       title = 'Earth: "Mostly Harmless"'
    [% tt_end_tag %]
    <a href="[% tt_start_tag %] path [% tt_end_tag %]?back=[% tt_start_tag %] back | uri [% tt_end_tag %]&title=[% tt_start_tag %] title | uri [% tt_end_tag %]">

The output generated is rather long so we'll show it split across two lines:

    <a href="http://tt2.org/example?back=%2Fother%3Ffoo%3Dbar%26
    baz%3Dbam&title=Earth%3A%20%22Mostly%20Harmless%22">

Without the uri filter the output would look like this (also split across two lines).

    <a href="http://tt2.org/example?back=/other?foo=bar
    &baz=bam&title=Earth: "Mostly Harmless"">

In this rather contrived example we've manage to generate both a broken URL (the repeated '?' is not allowed) and a broken HTML element (the href attribute is terminated by the first '"' after 'Earth: ' leaving 'Mostly Harmless"' dangling on the end of the tag in precisely the way that harmless things shouldn't dangle). So don't do that. Always use the uri filter to encode your URL parameters.

However, you should not use the uri filter to encode an entire URL.

   <a href="[% tt_start_tag %] page_url | uri [% tt_end_tag %]">   # WRONG!

This will incorrectly encode any reserved characters like ':' and '/' and that's almost certainly not what you want in this case. Instead you should use the url (note spelling) filter for this purpose.

   <a href="[% tt_start_tag %] page_url | url [% tt_end_tag %]">   # CORRECT

Please note that this behaviour was changed in version 2.16 of the Template Toolkit. Prior to that, the uri filter did not encode the reserved characters, making it technically incorrect according to the RFC 2396 specification. So we fixed it in 2.16 and provided the url filter to implement the old behaviour of not encoding reserved characters.

[%- END %] [% WRAPPER subsection title = "url" -%]

The url filter is a less aggressive version of the uri filter. It encodes any characters outside of the permitted URI character set (as defined by RFC 2396) into '%nn' hex escapes. However, unlike the uri filter, the url filter does not encode the reserved characters '&', '@', '/', ';', ':', '=', '+', '?' and '$'.

[%- END %] [% WRAPPER subsection title = "indent(pad)" -%]

Indents the text block by a fixed pad string or width. The 'pad' argument can be specified as a string, or as a numerical value to indicate a pad width (spaces). Defaults to 4 spaces if unspecified.

    [% tt_start_tag %] FILTER indent('ME> ') [% tt_end_tag %]
    blah blah blah
    cabbages, rhubard, onions
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    ME> blah blah blah
    ME> cabbages, rhubard, onions
[%- END %] [% WRAPPER subsection title = "truncate(length,dots)" -%]

Truncates the text block to the length specified, or a default length of 32. Truncated text will be terminated with '...' (i.e. the '...' falls inside the required length, rather than appending to it).

    [% tt_start_tag %] FILTER truncate(21) [% tt_end_tag %]
    I have much to say on this matter that has previously 
    been said on more than one occasion.
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    I have much to say...

If you want to use something other than '...' you can pass that as a second argument.

    [% tt_start_tag %] FILTER truncate(26, '&hellip;') [% tt_end_tag %]
    I have much to say on this matter that has previously 
    been said on more than one occasion.
    [% tt_start_tag %] END [% tt_end_tag %]

output:

    I have much to say&hellip;
[%- END %] [% WRAPPER subsection title = "repeat(iterations)" -%]

Repeats the text block for as many iterations as are specified (default: 1).

    [% tt_start_tag %] FILTER repeat(3) [% tt_end_tag %]
    We want more beer and we want more beer,
    [% tt_start_tag %] END [% tt_end_tag %]
    We are the more beer wanters!

output:

    We want more beer and we want more beer,
    We want more beer and we want more beer,
    We want more beer and we want more beer,
    We are the more beer wanters!
[%- END %] [% WRAPPER subsection title = "remove(string) " -%]

Searches the input text for any occurrences of the specified string and removes them. A Perl regular expression may be specified as the search string.

    [% tt_start_tag %] "The  cat  sat  on  the  mat" FILTER remove('\s+') [% tt_end_tag %]

output:

    Thecatsatonthemat
[%- END %] [% WRAPPER subsection title = "replace(search, replace) " -%]

Similar to the remove filter described above, but taking a second parameter which is used as a replacement string for instances of the search string.

    [% tt_start_tag %] "The  cat  sat  on  the  mat" | replace('\s+', '_') [% tt_end_tag %]

output:

    The_cat_sat_on_the_mat
[%- END %] [% WRAPPER subsection title = "redirect(file, options)" -%]

The 'redirect' filter redirects the output of the block into a separate file, specified relative to the OUTPUT_PATH configuration item.

    [% tt_start_tag %] FOREACH user = myorg.userlist [% tt_end_tag %]
       [% tt_start_tag %] FILTER redirect("users/${user.id}.html") [% tt_end_tag %]
          [% tt_start_tag %] INCLUDE userinfo [% tt_end_tag %]
       [% tt_start_tag %] END [% tt_end_tag %]
    [% tt_start_tag %] END [% tt_end_tag %]

or more succinctly, using side-effect notation:

    [% tt_start_tag %] INCLUDE userinfo 
         FILTER redirect("users/${user.id}.html")
	   FOREACH user = myorg.userlist 
    [% tt_end_tag %]

A 'file' exception will be thrown if the OUTPUT_PATH option is undefined.

An optional 'binmode' argument can follow the filename to explicitly set the output file to binary mode.

    [% tt_start_tag %] PROCESS my/png/generator 
         FILTER redirect("images/logo.png", binmode=1) [% tt_end_tag %]

For backwards compatibility with earlier versions, a single true/false value can be used to set binary mode.

    [% tt_start_tag %] PROCESS my/png/generator 
         FILTER redirect("images/logo.png", 1) [% tt_end_tag %]

For the sake of future compatibility and clarity, if nothing else, we would strongly recommend you explicitly use the named 'binmode' option as shown in the first example.

[%- END %] [% WRAPPER subsection title = "eval / evaltt" -%]

The 'eval' filter evaluates the block as template text, processing any directives embedded within it. This allows template variables to contain template fragments, or for some method to be provided for returning template fragments from an external source such as a database, which can then be processed in the template as required.

    my $vars  = {
	fragment => "The cat sat on the [% tt_start_tag %] place [% tt_end_tag %]",
    };
    $template->process($file, $vars);

The following example:

    [% tt_start_tag %] fragment | eval [% tt_end_tag %]

is therefore equivalent to

    The cat sat on the [% tt_start_tag %] place [% tt_end_tag %]

The 'evaltt' filter is provided as an alias for 'eval'.

[%- END %] [% WRAPPER subsection title = "perl / evalperl" -%]

The 'perl' filter evaluates the block as Perl code. The EVAL_PERL option must be set to a true value or a 'perl' exception will be thrown.

    [% tt_start_tag %] my_perl_code | perl [% tt_end_tag %]

In most cases, the [% tt_start_tag %] PERL [% tt_end_tag %] ... [% tt_start_tag %] END [% tt_end_tag %] block should suffice for evaluating Perl code, given that template directives are processed before being evaluate as Perl. Thus, the previous example could have been written in the more verbose form:

    [% tt_start_tag %] PERL [% tt_end_tag %]
    [% tt_start_tag %] my_perl_code [% tt_end_tag %]
    [% tt_start_tag %] END [% tt_end_tag %]

as well as

    [% tt_start_tag %] FILTER perl [% tt_end_tag %]
    [% tt_start_tag %] my_perl_code [% tt_end_tag %]
    [% tt_start_tag %] END [% tt_end_tag %]

The 'evalperl' filter is provided as an alias for 'perl' for backwards compatibility.

[%- END %] [% WRAPPER subsection title = "stdout(options)" -%]

The stdout filter prints the output generated by the enclosing block to STDOUT. The 'binmode' option can be passed as either a named parameter or a single argument to set STDOUT to binary mode (see the binmode perl function).

    [% tt_start_tag %] PROCESS something/cool
           FILTER stdout(binmode=1) # recommended [% tt_end_tag %]
    [% tt_start_tag %] PROCESS something/cool
           FILTER stdout(1)         # alternate [% tt_end_tag %]

The stdout filter can be used to force binmode on STDOUT, or also inside redirect, null or stderr blocks to make sure that particular output goes to stdout. See the null filter below for an example.

[%- END %] [% WRAPPER subsection title = "stderr" -%]

The stderr filter prints the output generated by the enclosing block to STDERR.

[%- END %] [% WRAPPER subsection title = "null" -%]

The null filter prints nothing. This is useful for plugins whose methods return values that you don't want to appear in the output. Rather than assigning every plugin method call to a dummy variable to silence it, you can wrap the block in a null filter:

    [% tt_start_tag %] FILTER null;
        USE im = GD.Image(100,100);
        black = im.colorAllocate(0,   0, 0);
        red   = im.colorAllocate(255,0,  0);
        blue  = im.colorAllocate(0,  0,  255);
        im.arc(50,50,95,75,0,360,blue);
        im.fill(50,50,red);
        im.png | stdout(1);
       END;
    -[% tt_end_tag %]

Notice the use of the stdout filter to ensure that a particular expression generates output to stdout (in this case in binary mode).

[%- END %] [% WRAPPER subsection title = "latex(outputType)" -%]

The latex() filter is no longer part of the core Template Toolkit distribution as of version 2.15. You can download it as a separate Template-Latex distribution from CPAN.

[%- END %] [%- END %] [% WRAPPER section title="AUTHOR" -%]

Andy Wardley <abw@wardley.org>

[% ttlink('http://wardley.org/', 'http://wardley.org/') -%]

[%- END %] [% WRAPPER section title="VERSION" -%]

2.86, distributed as part of the Template Toolkit version 2.19, released on 27 April 2007.

[%- END %] [% WRAPPER section title="COPYRIGHT" -%]
  Copyright (C) 1996-2007 Andy Wardley.  All Rights Reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

[%- END %] [% WRAPPER section title="SEE ALSO" -%]

[% ttlink('Template', 'Template') -%], [% ttlink('Template::Context', 'Template::Context') -%], [% ttlink('Template::Manual::Filters', 'Template::Manual::Filters') -%]

[%- END %]