On 9/12/07, Mitchell Jackson <[EMAIL PROTECTED]> wrote: > > 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; > > > > _______________________________________________ > List: Catalyst@lists.rawmode.org > Listinfo: http://lists.rawmode.org/mailman/listinfo/catalyst > Searchable archive: > http://www.mail-archive.com/catalyst@lists.rawmode.org/ > Dev site: http://dev.catalyst.perl.org/ >
Not to rain on your parade, but miyagawa++ has a plugin on the CPAN for this already: http://search.cpan.org/~miyagawa/Template-Plugin-Comma-0.04/lib/Template/Plugin/Comma.pm The more advanced Template::Plugin::Number::Format is probably more useful. -J -- J. Shirley :: [EMAIL PROTECTED] :: Killing two stones with one bird... http://www.toeat.com
_______________________________________________ List: Catalyst@lists.rawmode.org Listinfo: http://lists.rawmode.org/mailman/listinfo/catalyst Searchable archive: http://www.mail-archive.com/catalyst@lists.rawmode.org/ Dev site: http://dev.catalyst.perl.org/