Organizational Research By

Surprising Reserch Topic

how to get Current URI Segment in CodeIgniter


What would be the best way to check for the current URI segment in a CodeIgniter view? What I am trying to do is use the current URI segment [i.e. $this->uri->segment(1)] in order to highlight the current page on the navigation bar.

The best that I have figured out is to do

$data['current_uri'] = $this->uri->segment(1);
$this->load->view('header', $data);

in each of my controllers and then in the header.php file, I check the $current_uri variable to determine which part of the navigation should be highlighted. As you know, this is a very tedious way of doing it, but I'm at a loss of a better way to do this.


asked Jun 10, 2015 in codeinither by rajesh
0 votes
39 views



Related Hot Questions

1 Answer

0 votes

I myself use an extra function similar to anchor(). I call it active_anchor(), and it takes all the same parameters plus another (the uri). The function then adds the class 'active' if the uri string passed matches the active_anchor() url paramter.

Then the function returns using the anchor function (all that the function did was determine if the link needed the class 'active' or not.

EDIT:

I just put this code in a file called 'MY_url_helper.php'. That way, when the url helper is loaded (I actually auto load that one since pretty much all of my views use it anyway.) This is just some quick code too, pretty sure it would work. Basically it takes the same arguments as the anchor() function, but also the $key variable. It appends a class of "active" to the anchor tag if the key and url match.

php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('active_anchor'))
{
    function active_anchor($url = NULL, $title = NULL, $key = NULL, $params = array())
    {
        if ($url && $key)
        {
            if($key == $url)
            {
                if (array_key_exists ('class' , $params))
                {
                    $params['class'] .= ' active';
                }
                else
                {
                    $params['class'] = 'active';
                }
            }
        }
        return anchor($url, $title, $params);
    }
}

 

answered Jun 10, 2015 by rajesh

...