2013-04-10 107 views
0

我使用this solution作爲我的CakePHP 2.3網站的i18n。CakePHP獲取當前網址,不含語言前綴

當用戶在這個網址:

<a href="/eng<?php echo $this->here;?>">English</a> 

但是,當用戶在這個網址:example.com/fre/myController/myAction/param1/param2
example.com/myController/myAction/param1/param2
我想給鏈接example.com/eng/myController/myAction/param1/param2 這與我的視圖文件中的代碼運行良好不能鏈接到這個網址:example.com/eng/myController/myAction/param1/param2

我可以得到這個完整的URL:

fullURL = Router::url($this->here, true); 
$strippedURL = str_replace("http://example.com/fre/myController/myAction/param1/param2","myController/myAction/param1/param2",$fullURL) 

但我需要爲每種語言做到這一點。或者我可以從$fullURL中刪除前22個字符。但他們似乎不是很好的解決方案。 你有什麼建議嗎?

編輯:在我的助手/查看文件我用這個:

function getRelURL() { 
    $controller = $this->request->params['controller']; 
    $action = $this->request->params['action']; 
    $URL = "/".$controller."/".$action."/"; 
    foreach ($this->request->params['pass'] as $p) { 
     $URL .= urlencode($p)."/"; 
    } 
} 

我會很高興,如果你能推薦更好的選擇。

+0

我想我會計數斜槓和剝離所需的斜線前的一切。 – noslone 2013-04-11 07:08:31

+0

要使用您的路由(和**反向路由**),您應該*不*使用URL爲字符串生成鏈接,但*始終*使用數組表示法;例如'$ this-> Html-> link('home',array('controller'=>'pages','action'=>'view','home'));'。如果您想切換到另一種語言,請將'lang'鍵添加到陣列中,例如'array(........,'lang'=>'fre')'也讀:[靜態和動態內容國際化,路由和交換](http://bakery.cakephp.org/articles/ kicaj/2013/1月27日/ internationalization_with_static_and_dynamic_content_routing_and_switching) – thaJeztah 2013-04-11 18:52:30

回答

0

我使用了一種稍微不同的方法,即使我沒有使用命名參數和所有其他路由功能對其進行測試,它似乎也能正常工作。 我AppHelper創建了以下功能:

public function urlLanguage($lang) { 
    static $hereUrl=null; 

    if (empty($hereUrl)) { 
     $hereUrl = $this->request->params; 
     unset ($hereUrl ['models']); 
     unset ($hereUrl ['named']); 
     unset ($hereUrl ['paging']); 
     if (isset ($hereUrl ['pass'])) { 
      foreach ($hereUrl ['pass'] as $pass) { 
       $hereUrl [] = $pass; 
      } 
      unset ($hereUrl ['pass']); 
     } 
    } 
    return array_merge($hereUrl, array ('language' => $lang)); 
} 

和按如下方式使用它在瀏覽:

foreach ($languages as $lang=>$langDesc) { 
    echo $this->Html->link($languageDesc, $this->Html->urlLanguage($lang)); 
} 

其中$語言是所有可用語言的數組。我跳過鏈接本身的HTML。 我遵循指令here設置路線和語言切換。