Formatting timestamp field for output in TemplateToolkit

荒凉一梦 提交于 2019-12-04 15:14:37
Alexander Hartmaier

You configured DBIx::Class to inflate the value of the 'created' column to a DateTime object.

Note that you only need to load the TimeStamp component which is based on InflateColumn::DateTime, not both!

Furthermore you should add on_connect_call => 'datetime_setup' to your DBIx::Class connect_info to make DBIC set the database datetime format to match what it expects for the DateTime object inflation. This does the right thing for every supported database so it will also work if you switch database or use SQLite for testing.

Template::Plugin::Date is not for handling DateTime objects, Template::Plugin::DateTime is.

Regarding the template rendering I suggest you use Catalyst::View::TT#expose_methods feature by adding a method to your Catalyst::View::TT view which gets passed a DateTime object and returns a formatted string. You can add multiple methods for different formats, for example date + time, date only etc. This way you have a central location which defines the DateTime formatting which can be easily changed if needed.

This one should work:

[% date.format(xxx.created.strftime('%Y-%m-%d %H:%M:%S')) %]

Don't use the Date::Format function of Template Tookit, it doesn't work very well. Fortunately your DBIx::Class object can call strftime directly.

To fix your code example:

[% xxx.created.strftime( '%Y-%m-%d %R:%S' ) %]

For other formatting read the strftime manpage.

If you need to repeat the reformatting you might want to use a macro like this:

[% MACRO disp_dt(dt) BLOCK; dt.strftime( '%Y: %B %d' ) ; END %]

[% disp_dt( xxx.created ) %]

Thanks to MST for helping me with this on IRC.

date.format(xxx.created.replace('T', ' '));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!