[Templates] Filters + replace

Andy Wardley abw@wardley.org
Sat, 29 Jul 2006 10:49:35 +0100


Andrew Black wrote:
> In terms of writing my own filters I am still a bit confused.  There 
> seems to be difference between the way described in Template::Filters
> and Template::Plugin::Filters.

If you write a "regular" filter then you need access to the
Template object up-front, like so:

   my $tt = Template->new({
	FILTERS => { ... }
   });

That doesn't work with ttree or tpage unless you define your own
custom Template module like so:

   package My::Template;
   use base 'Template';
   sub new {
       my $class = shift;
       my $self  = $class->SUPER::new(@_);
       $self->context->define_filter(...);
       return $self;
   }

Then you can use your custom template module with the --template_module
option.

   $ ttree --template_module My::Template

Alternately, write a plugin filter, subclassing it from
Template::Plugin::Filter, and providing your own filter()
method.

Then you can load the filter anywhere with a

   [% USE MyFilter %]

This loads the plugin which installs the filter for you.  This way
you don't need to mess with any tpage/ttree options.

HTH
A