Skip to content

Instantly share code, notes, and snippets.

@animecyc
Created July 10, 2012 16:38
Show Gist options
  • Save animecyc/3084533 to your computer and use it in GitHub Desktop.
Save animecyc/3084533 to your computer and use it in GitHub Desktop.
Laravel Menu Generator
<?php
class Menu {
public static $menus = array();
public static function render($name)
{
return self::$menus[$name];
}
public static function register($name, Array $menu, $params = array())
{
$implode = function($glue, $separator, $array)
{
if(! is_array($array))
{
return $array;
}
$string = array();
foreach($array AS $key => $val)
{
if(is_array($val))
{
$val = implode(' ', $val);
}
$string[] = ' ' . $key . $glue . $val . $separator;
}
return implode($separator, $string);
};
$build = function($input, $options = array(), $html = '', $level = 1) use (&$build, $implode)
{
$html = $html ?: '';
if($level < 2) {
$options = array_merge_recursive(array(
'list_tag' => 'ul',
'item_tag' => 'li',
'after_link_with_children' => ' <b class="caret"></b>',
'attributes' => array(
'list' => array('class' => array('nav')),
'list_sub' => array('class' => 'dropdown-menu'),
'item' => array(),
'item_with_children' => array('class' => 'dropdown'),
'item_active' => array('class' => 'active'),
'item_parent_active' => array('class' => 'active'),
'link_with_children' => array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown')
)
), $options);
}
$html .= '<' . $options['list_tag'] . $implode('="', '"', $options['attributes'][$level == 1 ? 'list' : 'list_sub']) . '>';
foreach($input AS $item)
{
$children = false;
$item_active = false;
@ list($name, $link, $children) = $item;
if(preg_match('%^' . preg_quote($link) . '$%', URI::current(), $m))
{
$item_active = true;
}
if(count($children))
{
$html .= '<' . $options['item_tag'] . $implode('="', '"', $options['attributes']['item_with_children']) . '>';
$html .= '<a href="' . URL::to($link) . '"' . $implode('="', '"', $options['attributes']['link_with_children']) . '>' . $name . $options['after_link_with_children'] . '</a>';
$html .= $build($children, $options, '', ++$level);
--$level;
}
else
{
$html .= '<' . $options['item_tag'] . $implode('="', '"', $options['attributes']['item'] + ($item_active ? $options['attributes']['item_active'] : array())) . '>';
$html .= HTML::link($link, $name);
}
$html .= '</' . $options['item_tag'] . '>';
}
$html .= '</' . $options['list_tag'] . '>';
return $html;
};
self::$menus[$name] = $build($menu, $params);
return new self;
}
}
<?php
Autoloader::map(array(
'Menu' => __DIR__ . DS . 'menu' . EXT,
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment