问题
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');
Before middleware:
// 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.
I want:
If user insert this URL: /es/foo then all is ok.
If user insert this URL: /fr/foo then he must be redirect to /en.
Thanks.
回答1:
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
);
}
回答2:
I have found this solution:
$locale = $request->getLocale();
$allowLocale = ['en','es','de'];
if (!in_array($locale, $allowLocale)) {
$defaultLanguage = 'en';
$targetUrl = $app['url_generator']->generate('homepage');
$request->setLocale($defaultLanguage);
$app['translator']->setLocale($defaultLanguage);
$targetUrl = str_replace("/$locale/", "/$defaultLanguage/", $targetUrl);
return $app->redirect($targetUrl, 301);
}
But I would like to implement other solution more elegant.
What do you think guys?
来源:https://stackoverflow.com/questions/39034947/silex-redirect-changing-the-locale