Reputation: 30471
Do you know of a way how to check if current_url()
is equivalent to a link's href without using javascript? In doing so, if the href is the same then add class="active"
to the link.
Edit: The first thing which comes to mind is making an array of all href values then using foreach
to compare each one but maybe you have a better way than this?
Upvotes: 1
Views: 751
Reputation: 20469
(Posted the solution on behalf of the question author, to move it from the question to the answer space).
Answer thanks to Nick Pyett:
if(!function_exists('anchor')){
function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE){
if(!is_array($uri)){
$site_url = (!preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else {
$site_url = site_url($uri);
}
$title = (bool)$title ? $title : $site_url;
if($attributes != '') $attributes = _parse_attributes($attributes);
$active = $uri == uri_string() && $apply_active ? ' class="'.$apply_active.'"' : NULL;
return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>';
}
}
Upvotes: -1
Reputation: 3408
You could extend the anchor function in the URL helper like this.
if ( ! function_exists('anchor'))
{
function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE)
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($title == '')
{
$title = $site_url;
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
if ( $uri == uri_string() AND $apply_active )
{
$active = ' class="'.$apply_active.'"';
}
else $active = NULL;
return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>';
}
}
I haven't tested this so check a look for bugs. Call the anchor function like this:
anchor('my_page', 'My Page', '', 'active');
See the docs for how to extend helpers: http://ellislab.com/codeigniter/user_guide/general/helpers.html
Edit: OK I've tested it and updated my answer so it should work well now.
Upvotes: 1