How can you translate the Symfony response from a frontend application ?

published at Dec 15, 2019
#Symfony

Define the locale in a Kernel Subscriber, using the Accept-Language header to translate the response.

Just create a LocaleSubscriber in your Symfony project

<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class LocaleSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array(array('onKernelRequest', 200)),
        );
    }
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->headers->has("Accept-Language")) {
            $locale = $request->headers->get('Accept-Language');
            $request->setLocale($locale);
        }
    }
}

Then, from your frontend application, you just have to define the Accept-Language header to let Symfony know about the language you want.