Simplify rendering, building and maintenance of simple, dynamic standardised navigation menus. Instead of...
<? if ($user->get_role() === Role::ANONYMOUS):?>
<ul>
<li><a href="/" <?= $page === 'home' ? 'class="active"' : NULL?>>Home</a></li>
<li><a href="/about" <?= $page === 'about' ? 'class="active"' : NULL?>>About</a></li>
</ul>
<? // elseif (...)?>
... we do this:
<?
return [
'items' => [
'url' => 'home',
'title' => 'Home',
],
[
'url' => 'about',
'title' => 'About',
],
];
You define your menus in Kohana configuration files (see config/menu/navbar.php). Then, in your (main) controller (or template), you construct a new Menu object, set the active link and render it in your template. Done.
A WordPress type blog might have...
- Public main navigation menu
- Public footer menu
- Admin-only menu on the public pages, when admin is logged in
- Admin-only menu on the administrator interface
Normally, you'd build HTML views with ul
and li
elements and then write some PHP to highlight the active link. This is
difficult to maintain (DRY) and too much hassle (not to mention ugly).
Instead, describe your (standardised) menus in configuration files and have Kohana do the heavy lifting.
git clone git://github.com/anroots/kohana-menu.git modules/menu
As a Composer dependency
{
"require": {
"php": ">=5.4.0",
"composer/installers": "*",
"anroots/menu":"2.*"
}
}
<?php
Kohana::modules(array(
...
'menu' => MODPATH.'menu',
));
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<?=(string)Menu::factory('navbar')?>
</div>
</div>
</div>
You might wish to instantiate the menu in your main controller, since this gives you a way to interact with the Menu object before it's rendered.
You can use different config files by setting the factory's $config
parameter.
The view
key of the config files sets the view file that will be used to render the menu.
It defaults to a view file based on the $config
parameter: /views/templates/menu/$config
and if that does not exist falls back on the included /views/templates/menu/default
view file.
For an example, see the included navbar.php
config file.
$menu = Menu::factory($role); // this could use `config/menu/(user|admin).php`
Use set_current()
to mark the current menu item in your controller
$menu->set_current('article/show');
The parameter of set_current()
is the URL value of the respective item or its (numeric) array key
The code is mostly commented and more help can be found on the Wiki.
The Kohana module started out as a fork of the original Kohana Menu module by Bastian Bräu, but is now independently developed under the MIT licence.