How to call the filter "time_diff" in Twig

How can I call the time_diff 'function in Twig

Code

{{ post.created_at|time_diff }} 

Output

 The filter "time_diff" does not exist 
+6
source share
4 answers

If you are using Symfony 2,

And I want to use part of the native Twig extension

You should declare as a service something like:

 services: twig.extension.date: class: Twig_Extensions_Extension_Date tags: - { name: twig.extension } 
+18
source

I suggest you use KnpTimeBundle

So you can just compare with the current date:

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

This is a comparison with another date:

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

Translation is enabled by default, just browse the translation files or add as needed.

Hope for this help

+2
source

Have you added the extension?

Before using this formatting, add the following line:

 $twig->addExtension(new Twig_Extensions_Extension_Date()); 
+1
source

First you need:

 composer require twig/extensions 

Then you need to register the date extension:

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

After that, you can use the time_diff filter. Everything in the docs

+1
source

All Articles