Silex重定向更改语言环境 [英] Silex redirect changing the locale
问题描述
我正在使用Silex 2,并且如果使用无效的语言环境加载了任何网址,我想使用默认语言环境重定向到首页.
I am using Silex 2 and I would like to redirect to homepage with default locale if any url is loaded using an invalid locale.
// homepage / root
$this->get('{_locale}/', function (Request $request) use ($app) {
return $app['twig']->render('index/index.html.twig', array());
})->bind('homepage');
在中间件之前:
// i18n Control
$locale = $request->getLocale();
$allowLocale = ['en','es','de'];
if (!in_array($locale, $allowLocale)) {
$request->setLocale('en');
$response = new \Symfony\Component\HttpFoundation\RedirectResponse($app['url_generator']->generate('homepage'), 301);
$response->prepare($request);
return $response->send();
}
但是这段代码会产生无限循环.
But this code produces an infinite loop.
我想要:
如果用户插入以下URL:/es/foo,那么一切正常.
If user insert this URL: /es/foo then all is ok.
如果用户输入以下URL:/fr/foo,则必须将其重定向到/en.
If user insert this URL: /fr/foo then he must be redirect to /en.
谢谢.
推荐答案
您可以执行相同的操作,但是很容易,因为可以将URL参数传递给url_generator服务.另外,为使您的应用更灵活,更不易出错,您还应该为全局配置( allowedLocales 和 defaultLanguage )使用容器:
You can do the same, but easily as you can pass the URL parameter to the url_generator service. Also to make your app more flexible and less error prone, you should embarace the container for global configurations (for allowedLocales and defaultLanguage):
// somewhere in your configuration
$app['defaultLanguage'] = 'en';
$app['allowedLocales'] = ['en','es','de']
// Then in your controller
$locale = $request->getLocale();
if (!in_array($locale, $app['allowLocales'])) {
$request->setLocale($app['defaultLanguage']);
$app['translator']->setLocale($app['defaultLanguage']);
return $app->redirect(
$app['url_generator']->generate('homepage', ["locale" => $app['defaultLanguage']]),
301
);
}
这篇关于Silex重定向更改语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!