symfony 2.8 locale重置每个请求

时间:2016-12-09 15:55:52

标签: php symfony locale symfony-2.8

示例:

我正在尝试将语言环境设置为英语:

public function innerPageAction(Request $request, $slug)
{        
    $request->setLocale('en');
    return $this->render('@App/Front/Default/inner.html.twig', [
        ...
    ]);
}

然后我回到主页

public function indexAction(Request $request)
{
    $locale = $request->getLocale();
    return $this->render('@App/Front/Default/home.html.twig', [
        'locale' => $locale,
    ]);
}

这会返回我的默认语言区域(' lt')。

我的配置文件如下:

parameters:
    locale: lt
framework:
    default_locale:  "%locale%"

我正在尝试将语言环境设为粘性,如下所述:http://symfony.com/doc/current/session/locale_sticky_session.html 但似乎它的设置区域设置始终为defaultLocale。为什么呢?

当我从内页移动到主页时,我将如何实现这一点,它将返回" en"不是默认语言环境" LT"?

2 个答案:

答案 0 :(得分:0)

$request->setLocale('en');

只是暂时的,这意味着它不会被持久化,因此当您访问另一个页面时,请求区域设置将采用配置文件中的默认值,如果您遵循此link(您提供的相同链接)

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 after the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
        );
    }
}

对每个请求执行onKernelRequest方法,如果在会话中设置了语言环境,则使用$ request-> setLocale($ locale)应用,这样你就会在每个页面上都有一个“粘性”语言环境。

答案 1 :(得分:0)

在您的事件中,侦听器(或订阅者)onKernelRequest需要一个额外的行:

post_install do |installer|

installer.pods_project.targets.each do |target|

target.build_configurations.each do |config|

config.build_settings['SWIFT_VERSION'] = '3.0'

   end

  end

end