2

I want my twig dates and numbers (eg. {{ number|numberformat}} )to be in a format that is chosen by my users.

In this question it was suggested to make a listener to set the default twig formats. I don't fully understand this approach, so im not sure if this code can be adapted to make sure that dates are shown in a chosen format? (i mean to have a method User::getDateFormat() ) Or would you recommend another approach?

Thanks!

Community
  • 1
  • 1
Ward Beullens
  • 393
  • 5
  • 18

1 Answers1

3

Inject user also and all will work like a charm

namespace MyApp\AppBundle\Services;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class TwigDateRequestListener
{
    protected $twig;
    protected $context;

    function __construct(\Twig_Environment $twig, SecurityContext $context) 
    {
        $this->twig = $twig;
        $this->context = $context;
    }

    public function onKernelRequest(GetResponseEvent $event) 
    {
        $user = $this->context->getToken()->getUser();
        $user_date_format = $user->//function to retrieve date settings
        $this->twig->getExtension('core')->setDateFormat('Y-m-d', '%d days');
    }
}

And remember to modify service definition

services:
    twigdate.listener.request:
        class: MyApp\AppBundle\Services\TwigDateRequestListener
        arguments: [@twig, @security.context]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

onKernelRequest is called when kernel.request event is raised (take a look to service definition and you'll probably understood this)

kernel.request is raised every time a page is raised at every request

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
  • Thanks for your answer! I can't seem to get even the answer to the original question work though. But i'll figure it out. – Ward Beullens Aug 14 '15 at 16:55