in reply to Template::Toolkit and Currency Formatting

I've been using something along the lines of this (with corresponding CSS) fairly successfully.

use strict; use Template (); use Scalar::Util qw( looks_like_number ); sub fmt_currency { my( $txt ) = @_; return $txt unless looks_like_number( $txt ); if( $txt < 0 ) { $txt = '<span class="neg">(' . abs( $txt ) . ')</span>' } else { ## maybe wrap $txt with a pos span . . . } return $txt; } my $t = Template->new( FILTERS => { fmt_currency => \&fmt_currency }, ## ... ); my $data = { qw/foo 1.23 bar -3.45 baz quux/ }; my %tmpl_src = <<EOT; [% foo | fmt_currency %] [% bar | fmt_currency %] [% baz | fmt_currenc +y %] EOT $t->process( \$tmpl_src, $data, \*STDOUT ); exit 0; __END__ 1.23 <span class="neg">(3.45)</span> quux

Update: If you need to get fancier (e.g. passing a sprintf-style format string) see the Template::Plugin::Filter documentation for how to write and specify dynamic filters. Also the badger book has a relevant section as well.

Update 2: OK, I was bored and wanted to see if I remembered how to do it. Dynamic version follows for those who're really interested.

#!/opt/local/bin/perl use strict; use Template (); use Scalar::Util qw( looks_like_number ); sub fmt_currency_factory { my ($ctx, $fmt) = @_; $fmt = "%0.4f" unless defined $fmt; return sub { my ($txt) = @_; return $txt unless looks_like_number($txt); my $val = sprintf( $fmt, abs($txt) ); if ( $txt < 0 ) { $txt = '<span class="neg">(' . $val . ')</span>'; } else { $txt = $val; } return $txt; } } my $t = Template->new( FILTERS => { fmt_currency => [ \&fmt_currency_factory, 1 ] }, ## ... ); my $data = { qw/foo 1.23 bar -3.45 baz quux/ }; my $tmpl_src = <<EOT; [% foo | fmt_currency %] [% bar | fmt_currency( "%0.1f" ) %] [% baz | fmt_currency %] EOT $t->process( \$tmpl_src, $data, \*STDOUT ) or die $t->error(); __END__ 1.2300 <span class="neg">(3.5)</span> quux

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Template::Toolkit and Currency Formatting
by greg_coates (Initiate) on Dec 18, 2008 at 04:19 UTC
    This is fantastic. Thanks!