3

如何在 Symfony 2.3 中更改语言环境?

我创建了这个控制器:

public function changelocaleAction($lang)
{
    $request = $this->get('request');
    $request->setLocale($lang);
    return $this->redirect($request->headers->get('referer'));
}

刷新页面时它不会显示更改。为什么?

4

1 回答 1

5

基于 Symfony2文档

namespace Acme\LocaleBundle\EventListener;

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;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->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)),
        );
    }
}

服务.yml

services:
    acme_locale.locale_listener:
        class: Acme\LocaleBundle\EventListener\LocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }

最后,您可以在控制器中使用:

$locale = $this->getRequest()->getLocale();

在此链接中,您有一个非常相似的问题。

于 2013-10-21T07:43:09.927 回答