Welcome Guest, Not a member yet? Register   Sign In
display_helper : makes links active according to current controller - very tiny piece of code
#7

[eluser]Philipp Gérard[/eluser]
Hey benoa,

I didn't have the chance to write the function properly, but the following (from scratch) works and surely shows what I meant. However, I am not 100% sure if it works properly in every environment (w/wo .htaccess etc.), needs more testing. Any feedback appreciated!

Best wishes,
Philipp

Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('active_anchor'))
{
    /**
     * Provides the same functionality as anchor() (part of the default url-helper from CI)
     * but adds class="active" (or subclass 'active' to existing classes) to make it easy
     * to flag navigation elements using CSS.
     *
     * @param string or array $path
     * @param string $text
     * @param array $attributes
     * @return string
     * @author Philipp Gérard
     */
    function active_anchor($path = '', $text = '', $attributes = array())
    {
        $CI =& get_instance();
        
        if(!is_array($path) AND is_string($path))
        {
            $path = explode('/', $path);
        }
        if(count($path) == 1 AND $path[0] == '')
        {
            return anchor($path, $text, $attributes);
        }
        else
        {
            $active = NULL;
            $segments = $CI->uri->segment_array();
            for($i = 1; $i < count($path); $i++)
            {
                if(isset($segments[$i]))
                {
                    if($segments[$i] == $path[$i])
                    {
                        $active = TRUE;
                    }
                    else
                    {
                        $active = FALSE;
                        break;
                    }
                }
            }
            if($active === TRUE)
            {
                if(!isset($attributes['class']) OR empty($attributes['class']))
                {
                    $attributes['class'] = 'active';
                }
                else
                {
                    $attributes['class'] .= ' active';
                }
            }
            return anchor($path, $text, $attributes);
        }
    }
}

?&gt;

Usage:

Code:
&lt;?= active_anchor('/user/login', 'Login'); ?&gt;

Returns:

Code:
<a href="http://yourdomain.com/user/login.html" class="active">Login</a>


Messages In This Thread
display_helper : makes links active according to current controller - very tiny piece of code - by El Forum - 11-27-2009, 06:23 AM



Theme © iAndrew 2016 - Forum software by © MyBB