tags:

views:

302

answers:

1

Maybe not the best explanation, but hear me out. Say I have the following in a config file called menu.php:

// Default controller is 'home' and default action is 'index'
return array(
   'items' => array(
      'Home' => '',
      'News' => 'news',
      'Resources' => 'resources',
   ),
);

I now want to print this out as a menu, which is pretty simple:

foreach(Kohana::config('menu.items') as $title => $uri)
{
    echo '<li>' . HTML::anchor($uri, $title) . '</li>';
}

However, I want to find the $uri that matches the current controller and action. And if the action is the default one or not. What I want to end up with is that menu item should have id="active-item" if it is the linking to the current controller, but the default action. And id="active-subitem if it is linking to the current controller and the action is not the default one. Hope that made sense...

Anyone able to help me out here? Both in how to do this in Kohana 3 and also how it should be done in Kohana 3. I'm sure there are lots of ways, but yeah... any help is welcome :)


Examples:

  • domain.com -- Home should be active-item since it is the default controller
  • domain.com/home -- Home should be active-item
  • domain.com/home/index -- Home should be active-item since index is the default action
  • domain.com/resources -- Resources should be active-item
  • domain.com/resources/get/7 -- Resources should be active-subitem since get is not the default action
A: 

You could do it a few ways

CSS

I often use this method. I attach a class to the body element of every page to identify.

HTML

<style type="text/css">
body.home #home-link {
    border: 3px solid red;
}
</style>

<body class="home">
<ul>
    <li id="home-link">Home</li>
</ul>
</body>

Advantages are it's simple to implement. Disadvantages are you need to list a lot of selectors, one for each section (not such a problem on a small brochure site).

Add via Controller

You can also add via controller

Controller

public function action_about() {

    $this->template->active = 'about';

}

View

foreach(Kohana::config('menu.items') as $title => $uri)
{
    echo '<li' . (($active === $uri) ? ' class="active"' : NULL) . '>' . HTML::anchor($uri, $title) . '</li>';
}

Then of course, you just style the list element with the class of active. Advantages are that you only define the CSS once.

alex