I'm working on a project using Symfony 3.0 version, and I added a place where users can see how many time ago did the item was added. To be able to use this, i added the date extension to the services.yml file like this:
twig.extension.date:
class: Twig_Extensions_Extension_Date
tags:
- { name: twig.extension }
Now I can use the following code: {{ answer.answeredAt|time_diff }}
and everything is right, because it shows for example "2 hours ago".
My problem is, that some of this "answers" can be added by a javascript call. I searched a bit and the best option was to render this twig bit in the controller as a string and send it back in the javascript response. This way:
$now = new \DateTime();
$template = $this->get('twig')->createTemplate('{{ answeredAt|time_diff }}');
$date = $template->render(['answeredAt' => $now]);
$response = new JsonResponse([
'answer' => [
'id' => $answer->getId(),
'text' => $answer->getText(),
'date' => $date
]
]);
I thought this should work fine, but it didn't. Although no error was trown, the date field always comes back empty. Do I need to do something special on services.yml to make the extensions available on controllers?
The problem is related to when the difference of dates does not exist, in other words, when both dates are the same, the functions will return blank, and that was misleading me into thinking something was wrong.
If you check my code I was looking for a difference between now and new \DateTime()
which is also now, so, no difference at all.
If you still want to show something to the user, just like my case, you can use the following code:
$date = $template->render(['answeredAt' => $now->modify('-1 second')]);
This will show to users: "1 second ago".