Search code examples
perlif-statementtemplate-toolkit

Template toolkit compare dates


In template toolkit I want to add some text based on whether the date of my item is in the past,future or today. I am getting a field from the database called myDate which is a date field which looks like the below. myDate: 2012-12-12

In my template I am trying to do something like this. But I can't get the template to run when I try. Is there a way to do this in template toolkit?

    [% USE date %]
    [% IF myDate < date.format %]
    past
    [% IF myDate > date.format %]
    future
    [% ELSE %]
    today
    [% END %]

Solution

  • Are you perhaps comparing apples and orang-utans?

    Is your myDate value a string or a DateTime object? Both sides of the expression need to be the same type, and DateTime does a lot of overloading so that you can compare DateTime objects using >, <= and so on. If one side of the expression is an object and the other is a string, you will run into problems.

    Secondly, date.format without a formatting string returns the default POSIX representation, which according to Template::Plugin::Date is '%H:%M:%S %d-%b-%Y', almost certainly not what you want.

    So if myDate is a DateTime, try:

    [% IF myDate < date.now %]
    

    and if it's definitely a string, try:

    [% IF myDate < date.format('%Y-%m-%d') %]
    

    Hope that helps.


    UPDATE

    I was referring to perl DateTime objects, not whether the field in the database is date or datetime. Generally, database dates or datetimes are 'inflated' to perl DateTime objects by the ORM (DBIC or whatever.) You haven't told us enough about the provenance of myDate to know. I suggest you display myDate and date.now in your template to debug further, ie:

    [%- "myDate = "; myDate; " date.now = "; date.now; "<br/>";
        myDate.strftime('I must be a DateTime object: %Y-%m-%d'); "<br/>";
        date.now.strftime('I must be a DateTime object: %Y-%m-%d'); "<br/>"; -%]