Posted by Arjun on Wednesday 15th January 2014

Manage or Highlight Active link or page in Codeigniter?

Active Link CodeIgniter beginners CodeIgniter Helper

I always use this CodeIgniter Helper for all of my CI projects to Highlight Current or active link in the menu bar.

How it works

The active_link() function simply accept the name of a controller as a parameter and it will check if the current controller is equal to the the given string, if it is equal it will return the active string, otherwise empty string. To get an active controller this function is using CI's router class's fetch_class() method. i.e.$CI->router->fetch_class();

CI Nav Helper

Create a file in applications/helper directory with nav_helper.php name.copy and paste the code you find below

<?php  
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
if ( ! function_exists('active_link'))
{
    function active_link($controller)
    {
        $CI = &get_instance();
         
        $class = $CI->router->fetch_class();
 
        return ($class == $controller) ? 'active' : '';
    }
}

How to load:

To use this Helper function, you have to load it. you can load it with two methods, one is controller level/method level and another one is global level.

	
  $this->load->helper('nav');

open the application/config/autoload.php

	
$autoload['helper'] = array('nav');

How to use it

<ul>
    <li class="<?php echo active_link('home'); ?>"><a href="<?php echo site_url('home'); ?>">Home</a></li>
    <li class="<?php echo active_link('about'); ?>"><a href="<?php echo site_url('about'); ?>">About</a></li>
</ul>