将路由器 URL 与 CakePHP 中的当前 URL 匹配


Matching Router URL with current URL in CakePHP

我有以下代码列出了用CakePHP构建的博客的标签:

$tagsList = $this->requestAction('/tags/listTags');
foreach ($tagsList as $tagsListTag) {
    echo '<li'. strpos($this->here, Router::url(array('controller'=>'tags','action'=>'view','slug'=>$tagsListTag['Tag']['slug'])) ? ' class="selected"' : '' ).'>'.$this->Html->link($tagsListTag['Tag']['title'],array('controller'=>'tags','action'=>'view','slug'=>$tagsListTag['Tag']['slug']),array('class'=>'tag')).'</li>';
}

我添加了一些逻辑来比较当前 URL,每个链接的路由器 URL 是什么,如果匹配,应该向<li>添加一类selected

然而,它不起作用,即使只呼应$this->hereRouter::url显示它们是相同的!他们在我添加类的方式上还有其他问题吗?

首先,您的括号设置不正确,您的代码片段将产生解析器错误。我认为此错误仅存在于此代码示例中?它应该看起来像这样:

'<li' . (strpos($this->here, Router::url(array(...))) ? ' class="selected"' : '') . '>'

另一个问题是strpos可以返回0needlehaystack 0的位置找到)以及布尔falseneedle找不到),并且由于0的计算结果为 false(请参阅 http://php.net/manual/en/language.types.boolean.php),如果 URL 在第一个字符处匹配,您的条件将失败。

因此,您要么也必须测试0,要么以不同的方式比较值。在测试URL时,您很可能希望匹配确切的URL,因此您可以简单地使用比较运算符===

$this->here === Router::url(...)

如果您只需要匹配URL的一部分,则可以保留strpos并严格匹配0

(strpos($this->here, Router::url(array(...))) === 0 ? '...' : '...')

这将匹配确切的 URL,以及以 needle 开头的所有 URL。