Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the 'time_diff' filter in Twig

How can I call the 'time_diff' function In Twig

The code

{{ post.created_at|time_diff }}

Output

The filter "time_diff" does not exist
like image 266
hassen zouari Avatar asked Nov 30 '15 14:11

hassen zouari


4 Answers

If you're using Symfony 2,

And want to use some of the native twig extension

You have to declare as service something like :

services:
    twig.extension.date:
       class: Twig_Extensions_Extension_Date
       tags:
            - { name: twig.extension }
like image 81
BENARD Patrick Avatar answered Oct 17 '22 19:10

BENARD Patrick


At first you need:

composer require twig/extensions

Then you need to register Date extension:

$twig->addExtension(new Twig_Extensions_Extension_Date());

After that you could use time_diff filter. All in docs

like image 31
Ilya Yarkovets Avatar answered Oct 17 '22 21:10

Ilya Yarkovets


I suggest You to use the KnpTimeBundle

So you can simply compare with the current date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(myEntity.getMyTimeField) }}

This compare with the another date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(myEntity.getMyTimeField , to ) }}

The translation is enabled by default, simply review the translations files or add as you need.

Hope this help

like image 3
Matteo Avatar answered Oct 17 '22 20:10

Matteo


Did you add the date extension?

Add the following line before using this formatting:

$twig->addExtension(new Twig_Extensions_Extension_Date());
like image 1
Jerodev Avatar answered Oct 17 '22 19:10

Jerodev