我正在尝试用symfony2创建一个双语应用程序。 我正在使用Doctrine行为和A2lixtranslationformbundle。 我有一个听众改变语言环境:
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)),
);
}
}
在twig模板中,我想通过会话参数检索翻译,看看我们有什么语言环境:
{{ entity.translate(app.session.get('_locale')).title }}
但是app.session.get('_ locale')并没有返回任何内容。问题是为什么twig中的会话没有得到这个属性我在监听器中测试它一切都很好。
答案 0 :(得分:1)
要在树枝中检索locale
,您可以使用以下代码段
{{ app.request.locale }}
你个案的将是
{{ entity.translate(app.request.locale).title }}