Cameron
Cameron

Reputation: 28803

Matching Router URL with current URL in CakePHP

I have the following code that lists tags for a blog built in 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>';
}

I've added a bit of logic that compares the current URL, with what the Router URL for each link would be and if it matches should add a class of selected to the <li>

However it's not worked, even though echoing just the $this->here and Router::url show them to be the same! Is their some other issue here with the way I am adding the class?

Upvotes: 0

Views: 470

Answers (1)

ndm
ndm

Reputation: 60463

First of all your parentheses aren't set correctly, your code snippet will produce a parser error. I assume this mistake only exists in this code example? It should look something like this:

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

The other problem would be that strpos can return 0 (needle is found at position 0 in haystack) as well as boolean false (needle not found), and since 0 evaluates to false (see http://php.net/manual/en/language.types.boolean.php) your condition will fail in case the URL matches at the first char.

So you either have to test for 0 too, or compare the values differently. When testing for URLs you most probably want to match the exact URL, so you could simply use the comparison operator === instead:

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

In case you need to match only parts of the URL, you could stay with strpos and match strictly against 0:

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

This would match the exact URL, as well as all URLs that start with needle.

Upvotes: 1

Related Questions