如果浏览器接受语言是 de_DE 或 de(德语),我们如何自动转到德语,否则转到英语(所有其他浏览器接受语言)?
我的听众
namespace xxxx
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class LocaleListener
{
private $container;
private $defaultLocale;
public function __construct(ContainerInterface $container, $defaultLocale)
{
$this->container = $container;
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
if (!$this->container->has('request')) {
return;
}
$request = $this->container->get('request');
$request->setLocale($request->getPreferredLanguage($this->defaultLocale));
}
}
服务.yml
my_locale_listener:
class: Wishbot\WebBundle\Listener\LocaleListener
tags: [{ name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 100 }]
arguments: [ @service_container, ['de','en' ] ]