【发布时间】:2021-09-28 14:41:35
【问题描述】:
我目前正在开发 symfony 5,并且我已经将我的网站完全翻译成多种语言。我有一个选择语言的按钮,但我希望网站的默认语言是用户(更准确地说是他的浏览器)的语言。 目前我已经找到了一个解决方案,但它根本不是最优的。
我所做的是,在我的索引中,我检查用户之前是否已经浏览过该网站,如果没有,我将他重定向到 change_locale 路由,该路由将有问题的语言作为参数(他输入仅当这是他第一次访问时的条件)
public function index(Request $request): Response
{
// If this is the first visit to the site, the default language is set according to the user's browser language
if (!$request->hasPreviousSession()) {
return $this->redirectToRoute('change_locale', ['locale' => strtolower(str_split($_SERVER['HTTP_ACCEPT_LANGUAGE'], 2)[0])]);
}
return $this->render('accueil/index.html.twig');
}
这里我只是简单的在会话中注册变量来改变语言。
而我的问题就在这一步之后。当用户简单地点击网站上的语言更改按钮时,他会返回上一页(他没有输入 if)。
但是,如果他第一次来站点,他是从索引重定向的,当他来这个路由时,他输入条件if (!$request->hasPreviousSession()) 和......这就是问题所在。因为如果他之前没有访问过任何东西,我无法将他重定向到他正在访问的页面。
/**
* @Route("/change-locale/{locale}", name="change_locale")
*/
public function changeLocale($locale, Request $request)
{
$request->getSession()->set('_locale', $locale); // Storing the requested language in the session
// If it's the first page visited by the user
if (!$request->headers->get('referer')) {
return $this->redirectToRoute('index');
}
// Back to the previous page
return $this->redirect($request->headers->get('referer'));
}
所以我尝试从我的change_locale 路由中删除此条件,并找到一种方法在请求的标头中添加指向上一页的属性'referer'。
在执行 redirectToRoute 到 change_locale 之前,我可以在我的索引中执行此操作。
【问题讨论】:
标签: php symfony redirect http-headers translation