请求中的 Symfony 2.3 语言环境翻译



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

我创建了这个控制器:

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

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

基于 Symfony2 文档:

namespace AcmeLocaleBundleEventListener;
use SymfonyComponentHttpKernelEventGetResponseEvent;
use SymfonyComponentHttpKernelKernelEvents;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
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: AcmeLocaleBundleEventListenerLocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }

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

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

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

最新更新