开发者

Show time delta in perl's template toolkit

I want to supply an integer to a Template::Toolkit template. This integer represents a number of seconds elapsed.

I want to format this number like so:

1       => "1 second ago"
2       => "2 seconds ago"
43342   => "12 hours, 2 minutes ago" # ignoring the remaining 42 seconds
4333342 => "1 month, 19 days ago" # ignoring the remaining 17h, 42m & 22s

I can't fin开发者_运维问答d a TT plugin that does this.

Will I need to do this formatting outside of the TT?

Thanks


I don't know about any such plugin, but you can define your own virtual method for scalars which will do this:

use Template;
my $tt = Template->new({ ... });

$tt->context->define_vmethod('scalar',
    'duration',
    sub {
        my $seconds = shift;
        # calculate the duration
        return $duration;
    }
);

Then in you template use it like this:

Duration: [% var.duration %]


There's some code that comes close, if you use DateTime::Duration to represent the duration. DateTime::Format::Human::Duration can do most of what you need, but will tend to include additional parts of the duration beyond what you are interested in. Because the formatter is an object, as is the duration, both can be injected into the template as variables. You also just use the duration units directly to do this in a template, but that could be a lot of logic.

Time::Duration does do a better precision thing, so it does provide for the limit to two unit types, but doesn't have an object interface, so you can't inject it directly as a variable, but it might be a good basis for a custom filter.

If it was me, I'd wrap the function I need into a new formatting class which takes the time you need, make an instance, and inject that as a variable into the template. It's typically easier to unit test that way.


You also could use any module that does date and time calculations. Either define_vmethod as showed above or just assign the instance of your Time calculation class to TT stash and use its methods right in your templates.

Example:

#perl
my $tpiece = Time::Piece->new();
$tt->process('my/template.tt', {tpiece=>$tpiece}, \$out);
...
#TT
[% tpiece.add_months(6); %]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜