我的网站运行的是 Symfony 主版本。到目前为止,我能够使用 LocalListener logic来自网站,由于代码与我的版本不兼容,略有不同。 (我认为)我只是这样简化了 onKernelRequest 方法:
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
if ($locale = $request->get('_locale')) {
$request->getSession()->set('_locale', $locale);
}
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
这样,我就可以使用 these paths 在我的页面上放置一个简单的语言选择器。 ,并且新语言将在第一次请求时应用。 (如果我离开“else”条件,就不会发生)
然后,我想考虑用户帐户中存储的区域设置,以防用户登录并在其个人资料中指定区域设置。所以我在函数中添加了这段代码:
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
$token = $this->container->get('security.context')->getToken();
if (is_object($token)) {
$user = $token->getUser();
if (is_object($user)) {
$userlocale = $user->getLocale();
if ($userlocale) {
$request->getSession()->set('_locale', $userlocale);
$request->setLocale($userlocale);
return;
}
}
}
if ($locale = $request->get('_locale')) {
$request->getSession()->set('_locale', $locale);
}
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
(编辑:抱歉缩进不好,不知何故 stackoverflow 不想正确缩进......)
基本上,它检查用户是否已登录,如果有,他或她是否设置了区域设置,如果设置了,则将区域设置设置为用户区域设置。现在这有效了,但是……不是立即有效。每当我登录或更改个人资料中的区域设置时,我到达的下一页仍然是之前设置的区域设置。仅当我加载新页面时,它才会正确更改其翻译,并在下一个请求时保持这种状态。
所以这是我的问题:我是否应该添加一些东西来使这些更改发生在那些登录后和个人资料编辑后请求上?
最佳答案
您不仅需要设置新的区域设置,还需要在执行此操作后重定向用户以使更改生效。
此外,it's not a good practice to store the locale in the session — you should keep the locale in the URL 。这样,重定向到具有正确区域设置的 URL 就更有意义了。
关于symfony - 用户区域设置在第一次请求时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18648320/