我正在尝试用 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)),
);
}
}
在树枝模板中,我想通过会话参数检索翻译以查看我们拥有的语言环境:
{{ entity.translate(app.session.get('_locale')).title }}
但是 app.session.get('_locale') 不会返回任何内容。为什么树枝中的会话没有得到这个属性是什么问题我已经在监听器中测试了它,一切看起来都很好。