Easy Menu Formatting in Codeigniter

Formatting menus with appropriate CSS classes to define their state is messy and cumbersome at best, especially when not using a CMS, but something that is very much required to make websites usable. As a regular user of codeigniter it's something I've been searching for a solution for (before bothering to roll my own) and fortunately I found a great solution: Steal the menu library from FuelCMS, full documentation here.

In this post I will give a simple example of generating the menu below using the FuelCMS Menu Class in Codeigniter.

Before (Plain HTML):

Basic Tabbed Menu

<nav id='main'>
    <ul class='clearfix'>
        <li><a href='/'>home</a></li>
        <li><a href='/customers'>customers</a></li>
        <li><a href='/jobs'>jobs / orders</a></li>
        <li><a href='/basket'>basket</a></li>
    </ul>
</nav>

After (Generated):

Tabular menu with CSS classes generated by Codeigniter

<nav id='main'>
<ul>
    <li class='first active'>
        <a href='/' title='Home'>Home</a>
    </li>
    <li>
        <a href='/customers' title='Customers'>Customers</a>
    </li>
    <li>
        <a href='/jobs' title='Jobs'>Jobs</a>
    </li>
    <li class='last'>
        <a href='/basket' title='Basket'>Basket</a>
    </li>
</ul>
</nav>

FuelCMS is a CMS based on Codeigniter, it also contains many libraries which can be used with codeigniter independently of FuelCMS in general Codeigniter applications. One of which is the Menu Class. It does many things other than just basic menus like breadcrumb trails and collapsible menus and page titles so serves my purposes very well.

Example Usage

Add the setup code in the constructor of each controller where $this->data is the data sent to the view. In the view $menu contains the prepared html menu.

function __construct()
{
    //Array of pages 'name of controller' => 'Displayed text'
    $this->menu_pages = array(
                    '' => 'Home',
                    'customers' => 'Customers',
                    'jobs' => 'Jobs',
                    'basket' => 'Basket'
                );

    //get the name of the active page
    $this->CI->load->library('uri');
    $this->active = $this->uri->segment(1);

    //setup the menu and load it ready for display in the view
    $this->data['menu'] = $this->menu->render($this->menu_pages, $this->active);
}