greg_coates has asked for the wisdom of the Perl Monks concerning the following question:

I'm using Template::Toolkit to generate web reports. I've searched high and low for a way to format currency values so that negative numbers are surrounded by parenthesis and positive numbers are not. I'm coming up empty. (I have successfully used the 'format' filter to format currency using negative signs, but that's not what I want.)

Does anyone know of a module that will do this? Barring that, can anyone point me to documentation as to how to write a filter for the toolkit?

  • Comment on Template::Toolkit and Currency Formatting

Replies are listed 'Best First'.
Re: Template::Toolkit and Currency Formatting
by Fletch (Bishop) on Dec 18, 2008 at 01:59 UTC

    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.

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

      This is fantastic. Thanks!
Re: Template::Toolkit and Currency Formatting
by locked_user sundialsvc4 (Abbot) on Dec 18, 2008 at 03:33 UTC

    “It's been a while, but...” isn't this what the notion of ‘filters’ supposed to be for?   That is to say... if a standard filter doesn't do what you want, then I think that “the designer's intent” would be that you would design your own, using a sub as-suggested by the previous reply.