[Templates] Modifying TT functions at run time

Mark Fowler mark@twoshortplanks.com
Mon, 4 Nov 2002 15:16:34 +0000 (GMT)


On 4 Nov 2002, Simon Wilcox wrote:

> Is it possible to add a function like this at runtime or should I just
> bite the bullet and write a plugin ?

There is no bullet to bite when writing plugins.  Stop pretending there 
is ;-).  This is what I'd do (warning, untested code):

package Template::Plugin::ImageSize;
use base qw(Template::Plugin)
use strict;
use warnings;

use Image::Size;

sub load {
  my ($class, $context) = @_;

  # set the vmethod in the stash
  $Template::Stash::SCALAR_OPS->{imgsize} = \&image_size;

  # and the same for a list op so that single element lists
  # can be used as scalars
  $Template::Stash::LIST_OPS->{imgsize} = \&image_size_list;

  # return the same class
  return $class;
}

sub image_size
{
 my $image = shift;
 return [imgsize($image)]
}

sub image_size_list
{
 my $list = shift;
 return image_size($list->[0]);
}

1;

__END__

This is adapted from the OccurancesV example from my Extending the
Template Toolkit talk[1] (which I could swear you sat though at least 
once.)  Darn, I really should find some time to write up things about 
that.

Reguards.

Mark.

[1] http://2shortplanks.com/talks/yapce2002/

-- 
s''  Mark Fowler                                     London.pm   Bath.pm
     http://www.twoshortplanks.com/              mark@twoshortplanks.com
';use Term'Cap;$t=Tgetent Term'Cap{};print$t->Tputs(cl);for$w(split/  +/
){for(0..30){$|=print$t->Tgoto(cm,$_,$y)." $w";select$k,$k,$k,.03}$y+=2}