我想重定向用戶:自動重定向用戶到當地頁
- 英語用戶:www.website.com/en/
- 法國用戶:www.website.com/fr/
如果用戶不是英語或法語,默認重定向:www.website.com/en/
就目前而言,我創建了一個LocaleListener
:
昏暗\ MxBundle \監聽\ LocaleListener.php:
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale, $availableLocales, $container)
{
$this->defaultLocale = $defaultLocale;
$this->availableLocales = $availableLocales;
$this->container= $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession())
{
$locale = $event->getRequest()->getPreferredLanguage($this->availableLocales);
$event->getRequest()->setLocale($locale);
$Session = $this->container->get('session');
$Session->set('_locale', $locale);
return;
}
# try to see if the locale has been set as a _locale routing parameter
if ($locale = $event->getRequest()->getPreferredLanguage($this->availableLocales)) {
$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 before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
的Symfony /應用/配置/ routing.yml中:
dim_mx:
resource: "@DimMxBundle/Resources/config/routing.yml"
prefix: /
dim_mx:
resource: "@DimMxBundle/Resources/config/routing.yml"
prefix: /{_locale}/
requirements:
_locale: en|fr
root:
pattern:/
defaults:
_controller: FrameworkBundle:Redirect:urlRedirect
path: /%locale%/
permanent: true
總之,我想將用戶重定向訪問www.website.com/en/如果是英文用戶或www.website.com/fr/如果是法文用戶。目前,所有用戶都被重定向到/ en /。
謝謝大家的幫助。
看看symfony2文檔http://symfony.com/doc/current/book/routing.html或在JMS I18N路由包http://jmsyst.com/bundles/JMSI18nRoutingBundle/master/configuration – sebbo
還有類似的問題在這裏:http://stackoverflow.com/questions/19484027/translations-in-symfony-2-3-locale-in-request和http://stackoverflow.com/questions/14903963/Symfony2的語言環境,語言,全頁的事件監聽器 – Diablo