PHP code example of zentlix / knp-menu

1. Go to this page and download the library: Download zentlix/knp-menu library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zentlix / knp-menu example snippets


protected const LOAD = [
    // ...
    \Spiral\KnpMenu\Bootloader\KnpMenuBootloader::class,
];

use App\Menu\Sidebar;
use App\Menu\TopBar;
use App\Menu\OtherMenu;
use Spiral\Core\Container\Autowire;

return [
    /**
     * -------------------------------------------------------------------------
     *  Default template for all menus
     * -------------------------------------------------------------------------
     */
    'template' => 'menu.twig',

    /**
     * -------------------------------------------------------------------------
     *  Template options for all menus
     * -------------------------------------------------------------------------
     */
    'template_options' => [
        'foo' => 'bar'
    ],

    /**
     * -------------------------------------------------------------------------
     *  Application menus list
     * -------------------------------------------------------------------------
     *
     *  As a key, you can specify the name of the menu, using this key you can get the menu.
     *  If the key is not specified, the fully qualified name of the class will be used as the key.
     */
    'menus' => [
        'sidebar' => Sidebar::class,
        'top-bar' => new Autowire(TopBar::class),
        'other' => new OtherMenu()
    ]
];

namespace App\Menu;

use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Spiral\KnpMenu\MenuInterface;

final class Sidebar implements MenuInterface
{
    public function __construct(
        private readonly FactoryInterface $factory
    ) {
    }

    public function create(array $options = []): ItemInterface
    {
        $menu = $this->factory->createItem('root');

        $menu->addChild('Home', ['route' => 'homepage']);
        $menu->addChild('Blog', ['uri' => '/posts']);
        $menu->addChild('Comments', ['uri' => '#comments']);
        $menu->addChild('Full URL', ['uri' => 'https://site.com/']);

        return $menu;
    }
}

namespace App\Bootloader;

use App\Menu\Sidebar;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\KnpMenu\Bootloader\KnpMenuBootloader;
use Spiral\KnpMenu\MenuRegistry;

final class MenuBootloader extends Bootloader
{
    protected const DEPENDENCIES = [
        KnpMenuBootloader::class
    ];

    public function boot(MenuRegistry $registry, Sidebar $menu): void
    {
        $registry->add('sidebar', $menu);
    }
}

{{ knp_menu_render('sidebar') }}

{{ knp_menu_render('sidebar', {'template': 'custom.twig'}) }}