Templat...:Filters(3)
π NAME π
Template::Manual::Filters(3) β the standard filters page from the User Contributed Perl Documentation. Yes bestie, it's literally a whole menu of Template Toolkit filters, and we're about to go through every single one. No cap. π«Ά
format(format) β¨
The format filter takes a format string as a parameter (as per printf()) and formats each line of text accordingly. It's giving "printf but make it a filter." π
[% FILTER format('<!-- %-40s -->') %]
This is a block of text filtered
through the above format.
[% END %]
Output:
<!-- This is a block of text filtered -->
<!-- through the above format. -->
upper π₯
Folds the input to UPPER CASE. Loud, proud, and fully caps-locked. π
[% "hello world" FILTER upper %]
Output:
HELLO WORLD
lower πΈ
Folds the input to lower case. Soft launch, lowercase era. β¨
[% "Hello World" FILTER lower %]
Output:
hello world
ucfirst π
Folds the first character of the input to UPPER CASE. Just the first one, bestie β main character energy for one letter. π
[% "hello" FILTER ucfirst %]
Output:
Hello
lcfirst π¦
Folds the first character of the input to lower case. One tiny lowercase moment. π«Ά
[% "HELLO" FILTER lcfirst %]
Output:
hELLO
trim π§
Trims any leading or trailing whitespace from the input text. It's particularly useful in conjunction with INCLUDE, PROCESS, etc., and has the same effect as the TRIM configuration option. Clean edges only. β¨
[% INCLUDE myfile | trim %]
collapse π
Collapses 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. It's the "stop yelling with your spaces" filter. π
[% FILTER collapse %]
The cat
sat on
the mat
[% END %]
Output:
The cat sat on the mat
html π
Converts the characters <, >, & and " to <, >, &, and " respectively, protecting them from being interpreted as representing HTML tags or entities. It's the safety rails of HTML output. π₯
[% FILTER html %]
Binary "<=>" returns -1, 0, or 1 depending on...
[% END %]
Output:
Binary "<=>" returns -1, 0, or 1 depending on...
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. It's the glow-up for entity coverage. π
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 '"é"'). If neither module is available on your system then an '"html_entity"' exception will be thrown reporting an appropriate message.
If you want to force TT to use one of the above modules in preference to the other, then call either of the Template::Filters class methods: use_html_entities() or use_apache_util().
use Template::Filters;
Template::Filters->use_html_entities;
For further information on HTML entity encoding, see <http://www.w3.org/TR/REC-html40/sgml/entities.html>.
xml π
Same as the html filter, but adds ' which is the fifth XML built-in entity. Little XML bonus entity, no big deal. β¨
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. Paragraph glow-up, slay. π
[% FILTER html_para %]
The cat sat on the mat.
Mary had a little lamb.
[% END %]
Output:
<p>
The cat sat on the mat.
</p>
<p>
Mary had a little lamb.
</p>
html_break / html_para_break π₯
Similar to the html_para filter described above, but uses the HTML tag sequence <br><br> to join paragraphs. Same paragraph energy, different join. π
[% FILTER html_break %]
The cat sat on the mat.
Mary had a little lamb.
[% END %]
Output:
The cat sat on the mat.
<br>
<br>
Mary had a little lamb.
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. Line breaks stay iconic. β¨
[% FILTER html_line_break %]
The cat sat on the mat.
Mary had a little lamb.
[% END %]
Output:
The cat sat on the mat.<br>
Mary had a little lamb.<br>
uri π
This filter URI escapes the input text, converting any characters outside of the permitted URI character set (as defined by RFC 3986) into a %nn hex escape. URL-safe era, periodt. π
[% 'my file.html' | uri %]
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:
[% path = 'http://tt2.org/example'
back = '/other?foo=bar&baz=bam'
title = 'Earth: "Mostly Harmless"'
%]
<a href="[% path %]?back=[% back | uri %]&title=[% title | uri %]">
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 managed 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. π
Bestie warning: do not use the uri filter to encode an entire URL. That's a different vibe and it goes wrong. π
<a href="[% page_url | uri %]"> # 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="[% page_url | url %]"> # 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 (since superceded by RFC2732 and RFC3986). So we fixed it in 2.16 and provided the url filter to implement the old behaviour of not encoding reserved characters.
As of version 2.28 of the Template Toolkit, the uri and url filters use the unsafe character set defined by RFC3986. This means that certain characters ((, ), *, !, ', and ") are now deemed unsafe and will be escaped as hex character sequences.
The ability to use the RFC3986 character set was added in 2.26 but not enabled by default; double quote was incorrectly deemed safe in 2.26 but correctly escaped in 2.27.
If you want to enable the old behaviour then call the use_rfc2732() method in Template::Filters
use Template::Filters
Template::Filters->use_rfc2732;
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 $. Chill URL encoding, basically. π«Ά
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. Pad it up, bestie. π
[% FILTER indent('ME> ') %]
blah blah blah
cabbages, rhubard, onions
[% END %]
Output:
ME> blah blah blah
ME> cabbages, rhubard, onions
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). It's the "keep it short, bestie" filter. π
[% FILTER truncate(21) %]
I have much to say on this matter that has previously
been said on more than one occasion.
[% END %]
Output:
I have much to say...
If you want to use something other than "..." you can pass that as a second argument.
[% FILTER truncate(26, '…') %]
I have much to say on this matter that has previously
been said on more than one occasion.
[% END %]
Output:
I have much to say…
repeat(iterations) π
Repeats the text block for as many iterations as are specified (default: 1). More beer, more repeat. π₯
[% FILTER repeat(3) %]
We want more beer and we want more beer,
[% END %]
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!
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. Gone. Deleted. Not in this timeline. π
[% "The cat sat on the mat" FILTER remove('\s+') %]
Output:
Thecatsatonthemat
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. Swap era, slay. π
[% "The cat sat on the mat" | replace('\s+', '_') %]
Output:
The_cat_sat_on_the_mat
π redirect(file, options) π
Okay bestie, redirect is the filter that takes whatever the block spits out and yeets it into its own separate file. Where does that file go? Itβs specified relative to the OUTPUT_PATH configuration item. Slay.
[% FOREACH user IN myorg.userlist %]
[% FILTER redirect("users/${user.id}.html") %]
[% INCLUDE userinfo %]
[% END %]
[% END %]
or more succinctly, using side-effect notation:
[% FOREACH user IN myorg.userlist;
INCLUDE userinfo
FILTER redirect("users/${user.id}.html");
END
%]
β οΈ If theOUTPUT_PATHoption is undefined, afileexception will be thrown. No cap, thatβs the vibe check.
An optional binmode argument can follow the filename to explicitly set the output file to binary mode.
[% PROCESS my/png/generator
FILTER redirect("images/logo.png", binmode=1) %]
For backwards compatibility with earlier versions, a single true/false value can be used to set binary mode.
[% PROCESS my/png/generator
FILTER redirect("images/logo.png", 1) %]
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. π
β¨ 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. Itβs giving βtemplate inceptionβ and honestly? Obsessed.
my $vars = {
fragment => "The cat sat on the [% place %]",
};
$template->process($file, $vars);
The following example:
[% fragment | eval %]
is therefore equivalent to
The cat sat on the [% place %]
The evaltt filter is provided as an alias for eval. Cute little twin energy. π«Ά
π₯ 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. So yeah, flip that switch first, bestie.
[% my_perl_code | perl %]
In most cases, the [% PERL %] ... [% END %] block should suffice for evaluating Perl code, given that template directives are processed before theyβre evaluated as Perl. Thus, the previous example could have been written in the more verbose form:
[% PERL %]
[% my_perl_code %]
[% END %]
as well as
[% FILTER perl %]
[% my_perl_code %]
[% END %]
The evalperl filter is provided as an alias for perl for backwards compatibility. Vintage compatibility behavior, but make it iconic. β
π 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).
[% PROCESS something/cool
FILTER stdout(binmode=1) # recommended %]
[% PROCESS something/cool
FILTER stdout(1) # alternate %]
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. Main character output behavior, honestly. π
πΈ stderr πΈ
The stderr filter prints the output generated by the enclosing block to STDERR. Thatβs it, thatβs the whole filter. Simple, effective, lowkey necessary. π
π
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:
[% 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;
-%]
Notice the use of the stdout filter to ensure that a particular expression generates output to STDOUT (in this case in binary mode). Itβs the βsilence the noise, keep the important bitβ combo, and it ate. πβ¨
Thatβs a wrap on this part, bestie π«Ά The footer vibes were source/version perl v5.42.0, dated 2024-06-23, from Templat...:Filters(3). Go make those templates iconic. ππ
π¦ where this page comes from
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms