> Was wondering if there is an easy way to format a
> number in template toolkit to pad each 1000 withn a
> comma..
>
> e.g 1000 become 1,000   and 1000000 becomes 1,000,000

The following is a regex I use frequently combined with the replace vmethod 
and a MACRO - both with Parser::CET regexes and without.

#!/usr/bin/perl

use strict;

use Template;

my $has_CET;
if (eval { require Template::Parser::CET }) {
    $has_CET = 1;
    Template::Parser::CET->activate;
}

my $t = Template->new;

my $doc = <<'EOF';
------------ Template alone --------------
[%- MACRO comma(str) BLOCK;
    str.replace('(?<=\d)(?=(?:\d\d\d)+(?:\z|\.))',",");
    END %]
[%- FOR i IN [1, 123123, 123123123123, 123, 1234] %]
[%- comma(i) %]
[% END %]
EOF

$t->process(\$doc);


if ($has_CET) {
    $doc = <<'EOF';
------------ Template with Parser::CET --------------
[%- MACRO comma(str) BLOCK; 
    str.replace(/(?<=\d)(?=(?:\d\d\d)+(?:\z|\.))/, ",");
    END %]
[%- FOR i IN [1, 123123, 123123123123, 123, 1234] %]
[%- comma(i) %]
[% END %]
EOF

    $t->process(\$doc) || print $t->error;
}

_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates

Reply via email to