Developing software in the Real World

Overriding the built-in Twig date filter

In one project that I’m working on, I’m using Twig and needed to format a date received from an API. The date string received is of the style “YYYYMMDD”, however date produced an unexpected output.

Consider this:

creates the output:

This surprised me. Then I thought about it some more and realised that the date filter is treating my date string as a unix timestamp. I investigated and discovered the problem in twig_date_converter:

This code tests to see if the dates string provided is a number (positive or negative) and then prepends an ‘@’ symbol to the front. This has the effect of informing DateTime‘s constructor to treat $date as a unix timestamp.

Unfortunately, twig_date_converter is a function and so I couldn’t override it, so I wrote my own extension that registers new date, date_modify filters and a new date function in order to solve my problem:

This class simply registers new date, date_modify filters and a new date function to replace the ones in Twig core and then is a direct copy of the functions twig_date_format_filter, twig_date_modify_filter and twig_date_converter with the functionality above removed.

I also needed to register this extension with the Twig_Environment using: $env->addExtension(new \My\Twig\Extension\DateExtension()); and I’m done.

now correctly outputs:

While, it’s a shame I can’t just override twig_date_converter, I’m glad that I can re-register the relevant Twig filters and function.

5 thoughts on “Overriding the built-in Twig date filter

  1. You *could*, I suppose, try to trick Twig by adding a '.' (or something that won't affect DateTime's parsing) to the end of your date string – it'll subvert the ctype_digit test thus making DateTime parse it for you.

    But that's no fun of course.

Comments are closed.