I'm trying to make a two language app with symfony2. I'm using Doctrine behavior and A2lixtranslationformbundle. I have a listener which listen to change the locale:
namespace George\CoreBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'en')
{
$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
//if ($locale = $request->attributes->get('_locale')) {
if ($locale = $request->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
In the twig template i want to retrieve the translation trough the session param to see what locale we have:
{{ entity.translate(app.session.get('_locale')).title }}
But the app.session.get('_locale') does not return nothing. What is the problem why the session in the twig do not get this property i have test it in the listener everything looks fine.
In order to retrive the locale
in twig you can use the following snippet
{{ app.request.locale }}
for your case will be
{{ entity.translate(app.request.locale).title }}