Re: Time Display/Formatting Question

Andy Wardley <[email protected]> Fri, 22 Aug 2014 12:29:59 +0100
Newsgroups gmane.comp.lang.perl.modules.template-toolkit
Message-ID <[email protected]>
Hi Benjamin,

 > I want to format this number of seconds as a number of minutes and a
> number of seconds. I would rather do this formatting within within the
> template than by altering the data in the hash from within my Perl script.

Perhaps the best approach is to define your own virtual method.

It's described here:

http://www.template-toolkit.org/docs/manual/VMethods.html#section_Defining_Custom_Virtual_Methods

Although that documentation is a little out of date.  There's a better 
way to do it in more recent versions, like this (untested):

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

   $tt->context->define_vmethod(
       text => hm => sub {
           my $seconds = shift;
           return sprintf("%d:%02d", int($seconds / 60), $seconds % 60);
       }
   );

Here we've defined a text (scalar) virtual method call 'hm'.

Then you can call it like this:

   [% data.$cdr.billsec.hm %]

Cheers
Andy