如何使用KNP Menu Bundle 2创建面包屑?

时间:2015-10-09 19:52:52

标签: symfony knpmenubundle knpmenu

所以我有一个如下例所示的菜单:

<?php namespace AppBundle\Menu;

use Doctrine\ORM\EntityManager;
use Knp\Menu\FactoryInterface;
use Knp\Menu\MenuFactory;

class AdminMenuBuilder
{

    public function sidebarMenu(FactoryInterface $factory, array $options)
    {
    $menu = $factory->createItem('root', array(
        'navbar' => true,
        'childrenAttributes' => [
            'class' => 'nav main-menu',
        ],
    ));


    $menu->addChild('Dashboard')
         ->setAttributes([
            'icon' =>'fa fa-dashboard',
            'class' => 'dropdown',
             'dropdown' => true
         ]);

    $menu['Dashboard']->addChild('Details', ['route' => 'app.admin.dashboard']);
    $menu['Dashboard']->addChild('Details 2', ['route' => 'app.admin.dashboard']);

    $menu->addChild('Users', ['route' => 'app.admin.dashboard.users'])
        ->setAttribute('icon', 'fa fa-users');


        return $menu;
    }
}

如何使用KNPMenuBundle v2创建面包圈?我使用的是symfony2 2.7.5

2 个答案:

答案 0 :(得分:2)

KnpMenuBundle 2.1.0(几周前发布)具有knp_menu_get_breadcrumbs_array()功能,您可以使用它。例如:

{% set item = knp_menu_get('some_menu_item') %}
{% set breadcrumbs = knp_menu_get_breadcrumbs_array(item) %}
{% for breadcrumb in breadcrumbs %}
  <a href="{{ breadcrumb.url }}">{{ breadcrumb.label }}</a>
{% endfor %}

答案 1 :(得分:0)

如果您有嵌套菜单,则上述解决方案无效。这是以递归方式返回活动菜单项数组的扩展名:

ViewContainerRef.createComponent()

使用示例:

<?php

namespace AnalyticsBundle\Twig;

use Knp\Menu\ItemInterface;
use Knp\Menu\Matcher\MatcherInterface;
use Knp\Menu\Twig\Helper;

/**
 * Class MenuExtension
 * @package AnalyticsBundle\Twig
 */
class MenuExtension extends \Twig_Extension
{
    private $helper;

    private $matcher;

    public function __construct(Helper $helper, MatcherInterface $matcher)
    {
        $this->helper = $helper;
        $this->matcher = $matcher;
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('analytics_get_current_menu_items', function($menu, array $path = array(), array $options = array()) {
                $menu = $this->helper->get($menu, $path, $options);
                return $this->getCurrentItems($menu);
            }),
        ];
    }

    private function getCurrentItems(ItemInterface $item)
    {
        $items = [];
        $getActiveItems = function (ItemInterface $item) use (&$getActiveItems, &$items) {
            if ($this->matcher->isCurrent($item)) {
                $items[] = $item;
                foreach ($item->getChildren() as $child) {
                    $getActiveItems($child);
                }
            }
        };
        $getActiveItems($item);
        return $items;
    }

    public function getName()
    {
        return 'analytics_menu';
    }
}