Filters with Template Toolkit

In the last days I've been preparing a web site where I want to show values in four different currencies, accordingly with the user choice, and keeping up with the current exchange quote. I do not want to talk about how to get those values, or what values or website I am building, but just share an experience I've got with Template Toolkit that made it easy to separate the values conversion from the core code.
The idea is to create a Template Toolkit filter, that filters variables in the template that needs conversion. This filter uses a rate value and a currency code to know how to compute the correct value, and how to format it.

I called this filter Currencify, and its code is something like this:
package GF::Template::Plugin::Currencify;

use warnings;
use strict;

use Template::Plugin::Filter;
use parent qw( Template::Plugin::Filter );


sub filter {
  my ($self, $text) = @_;

  my $args     = $self->{_ARGS};
  my $currency = $args->[0] || 'USD';
  my $rate     = $args->[1] || 1;

  $text = sprintf("%.3f", $text * $rate);

  if ($currency eq "EUR") { return "€ $text";    }
  elsif ($currency eq "GBP") {  return "£ $text";   }
  elsif ($currency eq "CHF") {  return "CHF $text";  }
  else {  return "\$ $text"; }

  return $text;
}
The arguments that are extracted in the beginning are the currency code (like EUR) and the rate to convert the value from USD to the supplied currency. The template, then, imports the filter with those arguments:
[% use Currencify currency rate %]
and in the template, it is just a matter of calling Currencify filter to all values that should be converted:
[% value | $Currencify %]
To fill in the template, you just need to supply the currency code, the rate, and all the values in USD.

2 Comments

Template::Toolkit vmethods and filters are really useful. I prefer vmethods mostly, which would look like [% value.curencify %]

Template::Plugin::FilterVMethods would help you, dpetrov. I am surprised to find that Richard Simões deleted it, though. But if you don’t mind getting it from BackPAN, well, there you go.

Leave a comment

About Alberto Simões

user-pic I blog about Perl. D'uh!