Template::Filters - Post-processing filters for template blocks
use Template::Filters;
$filters = Template::Filters->new(\%config);
($filter, $error) = $filters->fetch($name, \@args, $context);
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 => { ... }, });
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.
The FILTERS option should be specified as a reference to a hash array in which each key represents the name of a filter. The corresponding value should contain a reference to an array containing a subroutine reference and a flag which indicates if the filter is static (0) or dynamic (1). A filter may also be specified as a solitary subroutine reference and is assumed to be static.
$filters = Template::Filters->new({ FILTERS => { 'sfilt1' => \&static_filter, # static 'sfilt2' => [ \&static_filter, 0 ], # same as above 'dfilt1' => [ \&dyanamic_filter_factory, 1 ], }, });
Additional filters can be specified at any time by calling the define_filter() method on the current Template::Context object. The method accepts a filter name, a reference to a filter subroutine and an optional flag to indicate if the filter is dynamic.
my $context = $template->context(); $context->define_filter('new_html', \&new_html); $context->define_filter('new_repeat', \&new_repeat, 1);
Static filters are those where a single subroutine reference is used for all invocations of a particular filter. Filters that don't accept any configuration parameters (e.g. 'html') can be implemented statically. The subroutine reference is simply returned when that particular filter is requested. The subroutine is called to filter the output of a template block which is passed as the only argument. The subroutine should return the modified text.
sub static_filter { my $text = shift; # do something to modify $text... return $text; }
The following template fragment:
[% FILTER sfilt1 %] Blah blah blah. [% END %]
is approximately equivalent to:
&static_filter("\nBlah blah blah.\n");
Filters that can accept parameters (e.g. 'truncate') should be implemented dynamically. In this case, the subroutine is taken to be a filter 'factory' that is called to create a unique filter subroutine each time one is requested. A reference to the current Template::Context object is passed as the first parameter, followed by any additional parameters specified. The subroutine should return another subroutine reference (usually a closure) which implements the filter.
sub dynamic_filter_factory { my ($context, @args) = @_;
return sub { my $text = shift; # do something to modify $text... return $text; } }
The following template fragment:
[% FILTER dfilt1(123, 456) %] Blah blah blah [% END %]
is approximately equivalent to:
my $filter = &dynamic_filter_factory($context, 123, 456); &$filter("\nBlah blah blah.\n");
See the FILTER directive for further examples.
use Template::Constants qw( :debug );
my $template = Template->new({ DEBUG => DEBUG_FILTERS | DEBUG_PLUGINS, });
[% 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. -->
[% "hello world" FILTER upper %]
output:
HELLO WORLD
[% "Hello World" FILTER lower %]
output:
hello world
[% "hello" FILTER ucfirst %]
output:
Hello
[% "HELLO" FILTER lcfirst %]
output:
hELLO
[% INCLUDE myfile | trim %]
[% FILTER collapse %]
The cat
sat on
the mat
[% END %]
output:
The cat sat on the mat
[% FILTER html %] Binary "<=>" returns -1, 0, or 1 depending on... [% END %]
output:
Binary "<=>" returns -1, 0, or 1 depending on...
For further information on HTML entity encoding, see http://www.w3.org/TR/REC-html40/sgml/entities.html.
[% 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>
[% 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.
[% 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>
[% 'my file.html' | uri %]
output:
my%20file.html
Note that URI escaping isn't always enough when generating hyperlinks in an HTML document. The "&" character, for example, is valid in a URI and will not be escaped by the URI filter. In this case you should also filter the text through the 'html' filter.
<a href="[% filename | uri | html %]">click here</a>
[% FILTER indent('ME> ') %] blah blah blah cabbages, rhubard, onions [% END %]
output:
ME> blah blah blah ME> cabbages, rhubard, onions
[% 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...
[% 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!
[% "The cat sat on the mat" FILTER remove('\s+') %]
output:
Thecatsatonthemat
[% "The cat sat on the mat" | replace('\s+', '_') %]
output:
The_cat_sat_on_the_mat
[% FOREACH user = myorg.userlist %] [% FILTER redirect("users/${user.id}.html") %] [% INCLUDE userinfo %] [% END %] [% END %]
or more succinctly, using side-effect notation:
[% INCLUDE userinfo FILTER redirect("users/${user.id}.html") FOREACH user = myorg.userlist %]
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.
[% 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.
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'.
[% my_perl_code | perl %]
In most cases, the [% PERL %] ... [% END %] 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:
[% 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.
[% 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.
[% 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).
The text block should be a complete LaTeX source file.
[% FILTER latex("pdf") -%] \documentclass{article}
\begin{document}
\title{A Sample TT2 \LaTeX\ Source File} \author{Craig Barratt} \maketitle
\section{Introduction} This is some text.
\end{document} [% END -%]
The output will be a PDF file. You should be careful not to prepend or append any extraneous characters or text outside the FILTER block, since this text will wrap the (binary) output of the latex filter. Notice the END directive uses '-%]' for the END_TAG to remove the trailing new line.
One example where you might prepend text is in a CGI script where you might include the Content-Type before the latex output, eg:
Content-Type: application/pdf
[% FILTER latex("pdf") -%] \documentclass{article} \begin{document} ... \end{document} [% END -%]
In other cases you might use the redirect filter to put the output into a file, rather than delivering it to stdout. This might be suitable for batch scripts:
[% output = FILTER latex("pdf") -%] \documentclass{article} \begin{document} ... \end{document} [% END; output | redirect("document.pdf", 1) -%]
(Notice the second argument to redirect to force binary mode.)
Note that the latex filter runs one or two external programs, so it isn't very fast. But for modest documents the performance is adequate, even for interactive applications.
A error of type 'latex' will be thrown if there is an error reported by latex, pdflatex or dvips.
<http://www.andywardley.com/|http://www.andywardley.com/>
Copyright (C) 1996-2004 Andy Wardley. All Rights Reserved. Copyright (C) 1998-2002 Canon Research Centre Europe Ltd.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Закладки на сайте Проследить за страницей |
Created 1996-2024 by Maxim Chirkov Добавить, Поддержать, Вебмастеру |