I am trying to set a locale in Symfony and everything works fine except the places where I try to translate or generate route in the layout file. I created a listener so I can set the locale on every request.
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LocaleListener implements EventSubscriberInterface {
private $container;
private $defaultLocale;
public function __construct(ContainerInterface $container, $defaultLocale = 'en') {
$this->container = $container;
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event) {
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
$loc = $this->defaultLocale;
if ($locale = $request->attributes->get('_locale')) {
//$request->getSession()->set('lang', $locale);
$event->getRequest()->getSession()->set('_locale', $locale);
$event->getRequest()->setLocale($locale);
$loc = $locale;
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($this->defaultLocale);
$event->getRequest()->getSession()->set('_locale', $this->defaultLocale);
$loc = $this->defaultLocale;
}
$this->container->get('translator')->setLoc($loc);
}
public static function getSubscribedEvents() {
return array(
// must be registered after the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
);
}
}
If in the twig template I try to access the session variable with app.session.get('_locale') that stores the locale it is as it should be - I get the desired result. But when I try app.request.locale I get the default locale not the one that is in the url. And because of that all my routes are prefixed with the default locale and everything is translated with the default language. How can I get the locale from the url in my layout and generate routes and translations with it?