尽管Symfony 2.1宣称您可以通过Request或Session对象简单地设置语言环境,但是我从未设定成功,因为仅仅设置语言环境没有任何效果。
所以我最终使用了一个侦听器和twig路由来处理语言环境:
侦听器:
namespace FK\MyWebsiteBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
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;
}
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
static public function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
在service.xml中注册监听器:
<service id="fk.my.listener" class="FK\MyWebsiteBundle\Listener\LocaleListener">
<argument>%locale%</argument>
<tag name="kernel.event_subscriber"/>
</service>
路由必须如下所示:
homepage:
pattern: /{_locale}
defaults: { _controller: FKMyWebsiteBundle:Default:index, _locale: en }
requirements:
_locale: en|fr|zh
使用以下方式处理路由:
{% for locale in ['en', 'fr', 'zh'] %}
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : locale})) }}">
{% endfor %}
这样,当您点击更改语言的链接时,区域设置将自动设置。