How to call the 'time_diff' filter in Twig
Asked Answered
T

5

6

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
Temperance answered 30/11, 2015 at 14:59 Comment(1)
Did you register this extension ? $twig->addExtension(new Twig_Extensions_Extension_Date());Bonfire
B
20

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 }
Bonfire answered 30/11, 2015 at 15:9 Comment(0)
I
3

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

Invocate answered 30/11, 2015 at 15:6 Comment(2)
" Then you need to register Date extension " ; Where ?Temperance
Either as a service, or somewhere in Controllers, but first way is better.Invocate
P
3

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

Perpetual answered 30/11, 2015 at 15:13 Comment(3)
I've set the locale as IT, but the translation isn't done. Any suggestion?Hymanhymen
Using github.com/KnpLabs/KnpTimeBundle seems to be the best solution for today (symfony 5). No customization needed just run:composer require knplabs/knp-time-bundle and use it {{ date|ago }}Shien
Thanks @marcin to confirm after five years that the solution is still valid :)Perpetual
S
1

Did you add the date extension?

Add the following line before using this formatting:

$twig->addExtension(new Twig_Extensions_Extension_Date());
Stalemate answered 30/11, 2015 at 15:5 Comment(1)
" Add the following line before using this formatting: " , Where ;Temperance
I
0

Just install the time bundle, and the |ago filter will automatically work.

composer req knplabs/knp-time-bundle
{{ post.created_at|ago }}

The more modern way is to use stimulus https://www.stimulus-components.com/docs/stimulus-timeago

Then the time shown is accurate, even for a static page (e.g. a SPA).

Ilka answered 4/3, 2024 at 22:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.