Do, 24. September 2009 um 17:11 Uhr
Use regular ereg expressions in the pattern matching to be highlight a list item based on path.
Usage
First, add the Menu helper to the controller’s $helpers array.
class BakeriesController extends AppController {
var $helpers = array('Menu');
}
?>
Now, you can create the Menu Helper.
/**
* Menu Helper class file.
*
* Use regular ereg expressions in the pattern matching to be highlight a list item based on path.
*/
class MenuHelper extends Helper {
var $helpers = array('Html');
/**
* Creates a formatted LI element.
*
* ### Usage
*
* `echo $menu->item($html->link('Example Link', array('controller' => 'Examples', 'action' => 'view', 3)), '/examples/*', array('class' => 'myListClass'));`
*
* @param string $link Formatted link, if $link is not an anchor, parsed with the HtmlHelper::link() method.
* @param string $regex Regular ereg expression.
* @param array $attributes The options to use.
* @return string An `<li><a /></li>` element.
*/
function item($link, $regex = null, $attributes = array()) {
// Highlight class to be returned, default selected
$activeClass = 'selected';
if(!ereg('^<a', $link)) {
$link = $this->Html->link($link);
}
if(!isset($regex)) {
$regex = '^/$';
}
$currentPath = substr($this->Html->here, strlen($this->Html->base));
if (ereg($regex, $currentPath)) {
$attributes = array_merge_recursive($attributes, array('class' => $activeClass));
if(is_array($attributes)) {
$attributes = implode(' ', $attributes);
}
}
return $this->Html->tag('li', $link, $attributes);
}
}
View Template
<ul id="menu">
<?php
e($menu->item($html->link('Blog', '/blog'), '^/$|/blog*'));
e($menu->item($html->link('Example', 'exemples/jim'), '/examples/*', array('id' => 'exampleID', 'class' => 'exampleClass')));
e($menu->item($html->link('Work', array('controller' => 'Pages', 'action' => 'display', 'work')), '/work*'));
?>
</ul>
CSS
ul#menu li a {
color:#777;
}
ul#menu li a:hover,
ul#menu li.selected a {
color:#fff;
}
Kommentare
Hey, this helper is very useful for me. Many thanks! ;)
Thanks, your code was really helpful!
Kommentar verfassen
Ihr Kommentar wird vor Veröffentlichung gegengelesen.