2011-03-17 80 views
1

我想做一個鏈接將在佈局中改變語言。所以它應該適用於很多路線。symfony鏈接改變語言,並留在頁面上

例如 我是頁/ EN/Mymodule中

上的鏈接應該指向 /德/ Mymodule中 /FR/Mymodule中

我發現這裏的解決方案是:http:/ /oldforum.symfony-project.org/index.php/m/70452/

<?php echo link_to(
    'Germany', 
    '@default?' . http_build_query(array(
    'sf_culture' => 'de', 
    'module' => $sf_request->getParameter('module'), 
    'action' => $sf_request->getParameter('action')) 
), null, '&')) ?> 

問題是,我需要一個默認路由,而我不希望擁有它。

有什麼解決方案,我需要什麼?

+0

爲什麼不會要使用默認路由? – Pabloks 2011-03-17 18:13:42

回答

3
routing: 
    user_switch_culture: 
    url: /culture-change/:language 
    param: { module: user, changeCulture } 

在您的佈局模板:

<?php echo link_to(image_tag("flags/gb.gif"), "user_switch_culture", array("language"=>"en", "redirect"=>$sf_request->getUri())) ?> 

鏈接將產生:

http://example.com/culture-change/fr?redirect=http//example.com/fr/control-panel

在你的行動:

public function executeChangeCulture(sfWebRequest $request) 
{ 
    $oldCulture = $this->getUser()->getCulture(); 
    $newCulture = $request->getParameter("language"); 
    $this->getUser()->setCulture($newCulture); 
    return $this->redirect(str_replace('/'.$oldCulture.'/', '/'.$newCulture.'/', $request->getParameter("redirect"))); 
} 

就在我頭頂。應該工作...

不是很大:應該做重定向一些過濾器,確保它是正確的域名等

1

我認爲我有一個解決辦法:

$uri = sfContext::getInstance()->getRouting()->getCurrentRouteName(); 
    echo link_to('French', $uri, array('sf_culture'=>'fr')) . ' | '; 
    echo link_to('English', $uri, array('sf_culture'=>'en')) . ' | '; 
    echo link_to('German', $uri, array('sf_culture'=>'de')); 

它是一個很好的一個,或是否有更好的解決辦法?

+0

我編輯更好的解決方案 – Charles 2011-03-17 18:17:20

+0

這可能會導致問題,如果顯示在404頁面上。 – Maerlyn 2011-03-17 23:01:56

+0

請勿使用sfContext :: getInstance()(請參閱:http://webmozarts.com/2009/07/01/why-sfcontextgetinstance-is-bad/) – Flukey 2011-03-29 15:48:32

2

爲什麼不爲此做一個特定的操作?

public function executeChangeLanguage(sfWebRequest $request) 
{ 
    if (in_array($request->getParameter('lang'), sfConfig::get('app_site_languages')) 
    { 
    $this->getUser()->setCulture($request->getParameter('lang')); 
    } 

    // you can ask the browser for referrer or send a parameter to the change language action 
    // something like '/change-language?lang=ro&redirect=your page'. 
    // if you are sending a redirect parameter you must make sure that it's actually a page within your site 
    $referrer = $request->getReferer(); 
    // or $referrer = $request->getParameter('redirect'); 

    // you can further check the referrer here 
    return $this->redirect($referrer); 
} 
+0

以及例如,如果引用鏈接是谷歌? – Flukey 2011-03-29 15:46:58

+0

就像在最後的評論中說的那樣,你必須檢查引薦者 (參見評論'//你可以在這裏進一步檢查引用者的位置)。否則,有些人可能會將您的重定向用於他們自己的目的 – 2011-03-30 12:39:39