Remove requirement of global variables for menu loading in twig

This commit is contained in:
Kendrick Chan 2020-04-05 11:01:37 +08:00
parent 22cf20accb
commit eb79fbf0ea
5 changed files with 27 additions and 14 deletions

View file

@ -9,5 +9,6 @@ use Annotation;
*/
class Menu
{
public $group = 'main'; // default to main menu group
public $selected;
}

View file

@ -17,14 +17,12 @@ class MenuAnnotationListener
protected $annot_reader;
protected $menu_gen;
protected $twig;
protected $menu_id;
public function __construct(Reader $annot_reader, MenuGenerator $menu_gen, TwigEnvironment $twig, $menu_id)
public function __construct(Reader $annot_reader, MenuGenerator $menu_gen, TwigEnvironment $twig)
{
$this->annot_reader = $annot_reader;
$this->menu_gen = $menu_gen;
$this->twig = $twig;
$this->menu_id = $menu_id;
}
public function onKernelController(ControllerEvent $event)
@ -57,20 +55,21 @@ class MenuAnnotationListener
if ($annotation == null)
return;
$this->selectMenu($annotation->selected);
$this->selectMenu($annotation->group, $annotation->selected);
}
protected function selectMenu($selected)
protected function selectMenu($group_id, $selected)
{
$this->menu_gen->setSelected($group_id, $selected);
/*
// get menu
$menu = $this->menu_gen->getMenu($this->menu_id);
$menu = $this->menu_gen->getMenu($group_id);
// set menu selected
$sel = $menu['index']->get($selected);
if ($sel != null)
$sel->setSelected();
// create twig global variable
$this->twig->addGlobal('menu_' . $this->menu_id, $menu);
*/
}
}

View file

@ -13,7 +13,6 @@ services:
Catalyst\MenuBundle\EventListener\MenuAnnotationListener:
arguments:
$menu_gen: "@catalyst_menu.generator"
$menu_id: "main"
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

View file

@ -36,6 +36,18 @@ class Generator
return $this->menu_data[$menu_key];
}
public function setSelected($menu_key, $id)
{
if (!isset($this->menu_data[$menu_key]))
return false;
$sel = $this->menu_data[$menu_key]['index']->get($id);
if ($sel != null)
$sel->setSelected();
return true;
}
protected function processConfigs($data)
{
$pdata = [];
@ -63,8 +75,6 @@ class Generator
$index = $pdata[$group]['index'];
$menu = $pdata[$group]['menu'];
error_log(print_r($group_data, true));
// 2nd layer is group data
foreach ($group_data as $mi_data)
{
@ -73,7 +83,6 @@ class Generator
$mi_data['icon'] = null;
// instantiate
error_log(print_r($mi_data, true));
$mi = $this->newItem($index, $mi_data['id'], $mi_data['label'], $mi_data['icon']);
// acl

View file

@ -23,6 +23,11 @@ class MenuExtension extends AbstractExtension
public function getMenu($menu_group)
{
return $this->menu_gen->getMenu($menu_group);
$menu_data = $this->menu_gen->getMenu($menu_group);
if (isset($menu_data['menu']))
return $menu_data['menu'];
return [];
}
}