如何在Symfony 2.1中翻译语言,根据接受语言标题?

时间:2013-02-20 05:16:46

标签: symfony-2.1

如果浏览器接受语言为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));
    }
}

service.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' ] ]

1 个答案:

答案 0 :(得分:-1)

我建议你阅读Symfony 2文档中的翻译章节。

http://symfony.com/doc/2.0/book/translation.html

它将向您解释如何使用不同语言维护您的网站。