2016-12-09 33 views
0

例子:symfony的2.8場所正在重置每個請求

我想區域設置爲英語:

public function innerPageAction(Request $request, $slug) 
{   
    $request->setLocale('en'); 
    return $this->render('@App/Front/Default/inner.html.twig', [ 
     ... 
    ]); 
} 

然後我回到主頁

public function indexAction(Request $request) 
{ 
    $locale = $request->getLocale(); 
    return $this->render('@App/Front/Default/home.html.twig', [ 
     'locale' => $locale, 
    ]); 
} 

這將返回我的默認語言環境( '爲lt')。

我的配置文件看起來像:

parameters: 
    locale: lt 
framework: 
    default_locale: "%locale%" 

我試圖讓現場粘,因爲它是在這裏描述:http://symfony.com/doc/current/session/locale_sticky_session.html 但是似乎它的設置區域總是defaultLocale。爲什麼?

我如何實現當我從內頁移動到主頁時,它會返回「en」而不是默認語言環境「lt」?

回答

0
$request->setLocale('en'); 

只是暫時的意義是不持久的,所以當你訪問一個頁面請求的語言環境需要從配置文件中的默認值,如果按照這個link(您提供相同的鏈接)

class LocaleListener implements EventSubscriberInterface 
{ 
    private $defaultLocale; 

    public function __construct($defaultLocale = 'en') 
    { 
     $this->defaultLocale = $defaultLocale; 
    } 

    public function onKernelRequest(GetResponseEvent $event) 
    { 
     $request = $event->getRequest(); 
     if (!$request->hasPreviousSession()) { 
      return; 
     } 

     // try to see if the locale has been set as a _locale routing parameter 
     if ($locale = $request->attributes->get('_locale')) { 
      $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 after the default Locale listener 
      KernelEvents::REQUEST => array(array('onKernelRequest', 15)), 
     ); 
    } 
} 

onKernelRequest方法在每個請求上執行,如果區域設置是在會話中設置的,它使用$ request-> setLocale($ locale)應用,這樣每個頁面上都會有一個'sticky'語言環境。

+0

我明白這一點,但正如我所說,它不工作。我從來沒有這樣做過:$ request-> getSession() - > set('_ locale',$ locale);和$ request-> setLocale($ request-> getSession() - > get('_ locale',$ this-> defaultLocale));始終將區域設置設置爲'lt'。我不明白爲什麼。 – vyckiuz

0

在事件偵聽器(或訂戶)onKernelRequest需要一個額外的行:

// try to see if the locale has been set as a _locale routing parameter 
    if ($locale = $request->attributes->get('_locale')) { 
     $request->getSession()->set('_locale', $locale); 
     $request->setLocale($locale); // seems that it's SIGNIFICANT 
    } else { 
     // if no explicit locale has been set on this request, use one from the session 
     $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); 
    }