[Catalyst] TT VMethods

Mitchell Jackson mitch.lists at onsitesquad.com
Thu Sep 13 03:35:33 GMT 2007


Today I saw how easy it is to extend Template-Toolkit within Catalyst.  
Perhaps somebody here will find this useful.

I wanted to easily format dollar amounts from within the tt2 template.  
I had been doing this with [% FILTER format( "%.2f" ) %], but having 
FILTER/END everywhere seemed a bit annoying, and I wanted to add commas 
to make the data easier to read on large numbers.

In Catalyst, you can add extensions to Template from your app's lib 
directory.  You can add filters ( Template::Plugin::Filter ) and 
VMethods ( Template::Plugin::VMethods ) simply by putting them into 
MyApp/lib/Template/Plugin

Following is an example that adds a 'commify' method to any scalar 
template variable.  [% var.commify %] to add seperating commas, [% 
var.commify(2) %] to add commas and round to two decimal places

/Mitch
OnSite Mobile



#MyApp/lib/Template/Plugin/commify.pm
package Template::Plugin::commify;

use Template::Plugin::VMethods;
use base qw(Template::Plugin::VMethods);
@SCALAR_OPS = qw(commify);

=head1 commify

    VMethod extension to format a number with pretty commas each 3rd digit,
    and to specify decimal precision

    Template Syntax:
    [% USE commify %]
    [% test = '1234567890.983457' %]
    [% test.commify    %] 1,234,567,890.983457
    [% test.commify(2) %] 1,234,567,890.98

=cut

sub commify {
    my ( $data, $precision ) = @_;
    my $decimals;

    # don't do anything to the data if it doesn't look like a number
    return $data
        if $data !~ /^\d+(?:\.\d+)$/;

    # round to the specified precision
    $data = sprintf "%.${precision}f", $data
        if defined $precision;

    # detach the decimals, we don't want commas there
    $decimals = $1 if $data =~ s/(\.\d+)//;

    # insert commas
    $data =~ s/(\d{1,3})(?=(?:\d\d\d)+(?!\d))/$1,/g;

    # reattach decimals
    $data .= $decimals if defined $decimals;

    $data;
}

1;





More information about the Catalyst mailing list