【问题标题】:CakePHP get current URL without language prefixCakePHP 获取没有语言前缀的当前 URL
【发布时间】:2013-04-10 23:46:37
【问题描述】:

我在我的 CakePHP 2.3 网站的 i18n 中使用了 this solution

当用户在此 URL 中时:example.com/myController/myAction/param1/param2
我想给example.com/eng/myController/myAction/param1/param2的链接 这适用于我的视图文件中的这段代码:

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

但是当用户在这个 URL 中:example.com/fre/myController/myAction/param1/param2
我无法将他链接到此 URL: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 个字符。但它们似乎不是好的解决方案。 你有什么建议吗?

编辑:在我的 Helper/View 文件中,我使用了这个:

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)."/";
  }
}

如果您能推荐更好的选择,我会很高兴。

【问题讨论】:

  • 我想我会计算斜线并去掉所需斜线前面的所有内容。
  • 要使用您的路由(和 反向路由),您应该使用 URL 字符串生成链接,但 总是使用数组表示法;例如$this-&gt;Html-&gt;link('home', array('controller' =&gt; 'pages', 'action' =&gt; 'view', 'home'));。如果要切换到另一种语言,请将 lang 键添加到数组中,例如array(........, 'lang' =&gt; 'fre') 另请阅读:Internationalization with static and dynamic content, routing and switching

标签: php cakephp url-routing cakephp-2.3


【解决方案1】:

我使用了一种稍微不同的方法,似乎效果很好,尽管我没有使用命名参数和所有其他路由功能对其进行测试。 我在 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));
}

其中 $languages 是一个包含所有可用语言的数组。我跳过了链接本身的 HTML。 我按照here 的说明设置路线和语言切换。

【讨论】:

    猜你喜欢
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2023-04-02
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多