Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig – time ago format

Tags:

php

twig

I'm new to Twig and I'm looking to turn a datetime format into a time ago like 2 hours ago or 3 days ago. There is a jquery plugin (jquery-timeago) that I've been using on the client side but it would be great if I can do this with twig. If twig doesn't come with this filter format are there extensions that I can use?

like image 853
Mark S Avatar asked Oct 11 '14 04:10

Mark S


3 Answers

If you're using Twig inside of Symfony, check out KnpTimeBundle. Includes "ago" support in multiple languages.

like image 170
nurikabe Avatar answered Oct 01 '22 15:10

nurikabe


Twig's date extension does exactly what you ask:

{{ post.published_at|time_diff }}

The example above will output a string like 4 seconds ago or in 1 month, depending on the filtered date.

See http://twig.sensiolabs.org/doc/extensions/date.html (no longer works) Working link http://twig-extensions.readthedocs.io/en/latest/date.html

To make this work, follow these steps:

composer require twig/extensions

When working with symfony add this to your services.yml

services:
  twig.extension.date:
    class: Twig_Extensions_Extension_Date
    tags:
    - { name: twig.extension }
like image 36
10us Avatar answered Oct 01 '22 15:10

10us


I found out I can create a custom filter with twig 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 my Twig environment:

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

Use it my template like this:

{{2014-10-11 12:54:37|timeago}}
like image 30
Mark S Avatar answered Oct 01 '22 16:10

Mark S