Search code examples
perltimetemplate-toolkit

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 find a TT plugin that does this.

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

Thanks


Solution

  • 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.