Twig - Time ago Format

I am new to Twig and I want to turn the datetime format into the past, like 2 hours ago or 3 days ago . There is a jquery-plugin (jquery-timeago) that I use on the client side, but it would be great if I could do it with a branch. If twing is not included in this filter format, are there any extensions I can use?

+7
php twig
source share
3 answers

I found out that I can create my own Twig_SimpleFilter Twig_SimpleFilter .

 $filter = new Twig_SimpleFilter('timeago', function ($datetime) { $time = time() - strtotime($datetime); $units = array ( 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second' ); foreach ($units as $unit => $val) { if ($time < $unit) continue; $numberOfUnits = floor($time / $unit); return ($val == 'second')? 'a few seconds ago' : (($numberOfUnits>1) ? $numberOfUnits : 'a') .' '.$val.(($numberOfUnits>1) ? 's' : '').' ago'; } }); 

Then I add it to the Twig environment:

 $twig = $app->view()->getEnvironment();//because I'm using Twig in Slim framework $twig->addFilter($filter); 

Use it my template as follows:

 {{2014-10-11 12:54:37|timeago}} 
+12
source share

The Twig date extension does exactly what you ask for:

 {{ post.published_at|time_diff }} 

In the above example, a string of type 4 seconds ago or 1 month will be displayed, depending on the filtered date.

See http://twig.sensiolabs.org/doc/extensions/date.html (no longer working)

Working link http://twig-extensions.readthedocs.io/en/latest/date.html

+12
source share

If you use Twig inside Symfony, check out KnpTimeBundle . Includes back support in multiple languages.

+3
source share

All Articles