### Install KnpMenuBundle using Composer Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Use this command to add the KnpMenuBundle to your project. Requires Composer to be installed globally. ```bash composer require knplabs/knp-menu-bundle ``` -------------------------------- ### PHP Menu Builder Class Example Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_convention.rst Define a menu builder class within the 'Menu' directory of a bundle. Each method in this class corresponds to a menu, receiving a FactoryInterface and options. This example demonstrates creating a main menu with nested items and dynamic route parameters. ```php namespace AppBundle\Menu; use App\Entity\Blog; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; final class Builder { public function __construct( private EntityManagerInterface $em, ) { } public function mainMenu(FactoryInterface $factory, array $options): ItemInterface { $menu = $factory->createItem('root'); $menu->addChild('Home', ['route' => 'homepage']); // findMostRecent and Blog are just imaginary examples $blog = $this->em->getRepository(Blog::class)->findMostRecent(); $menu->addChild('Latest Blog Post', [ 'route' => 'blog_show', 'routeParameters' => ['id' => $blog->getId()] ]); // create another menu item $menu->addChild('About Me', ['route' => 'about']); // you can also add sub levels to your menus as follows $menu['About Me']->addChild('Edit profile', ['route' => 'edit_profile']); // ... add more children return $menu; } } ``` -------------------------------- ### YAML Translation Example Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/i18n.rst Example of how to define translations for menu items in YAML format for the 'fr' locale. ```yaml # translations/messages.fr.yaml Home: Accueil Login: Connexion ``` -------------------------------- ### Get and Render a Menu Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Retrieve a menu by its alias and render it. Ensure the menu alias exists. ```html+jinja {% set menuItem = knp_menu_get('my_main_menu') %} {{ knp_menu_render(menuItem) }} ``` ```html+php get('my_main_menu') ?> render($menuItem) ?> ``` -------------------------------- ### Render a menu with options using PHP templates Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Customize menu rendering by passing an array of options to the `render` method in PHP templates. This example sets `depth` and `currentAsLink`. ```html+php render('my_main_menu', [ 'depth' => 2, 'currentAsLink' => false, ]) ?> ``` -------------------------------- ### PHP Translation Example Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/i18n.rst Example of how to define translations for menu items in a PHP array format for the 'fr' locale. ```php // translations/messages.fr.php return [ 'Home' => 'Accueil', 'Login' => 'Connexion', ]; ``` -------------------------------- ### Get Menu with Builder Options Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Pass options to the menu builder when retrieving a menu. Options are passed as the third argument. ```html+jinja {% set menuItem = knp_menu_get('my_main_menu', [], {'some_option': 'my_value'}) %} {{ knp_menu_render(menuItem) }} ``` ```html+php get('my_main_menu', [], [ 'some_option' => 'my_value' ]) ?> render($menuItem) ?> ``` -------------------------------- ### Configure KnpMenuBundle in XML Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Configure the KnpMenuBundle using XML in `config/packages/knp_menu.xml`. This example disables templating and sets the default renderer to twig. ```xml ``` -------------------------------- ### XLIFF Translation Example Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/i18n.rst Example of how to define translations for menu items using the XLIFF format for the 'fr' locale. ```xml Home Accueil Login Connexion ``` -------------------------------- ### Configure KnpMenuBundle in PHP Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Configure the KnpMenuBundle programmatically in `config/packages/knp_menu.php`. This example disables the Twig extension and sets the default renderer. ```php // config/packages/knp_menu.php $container->loadFromExtension('knp_menu', [ // use 'twig' => false to disable the Twig extension and the TwigRenderer 'twig' => [ 'template' => 'KnpMenuBundle::menu.html.twig' ], // if true, enable the helper for PHP templates (deprecated) 'templating' => false, // the renderer to use, list is also available by default 'default_renderer' => 'twig', ]); ``` -------------------------------- ### Render Menu in Template Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_convention.rst Render a menu directly in a template using its conventional name, which follows the format 'bundle:class:method'. This example shows how to render the 'mainMenu' created in the 'App' bundle's 'Builder' class. ```html+jinja {{ knp_menu_render('App:Builder:mainMenu') }} ``` -------------------------------- ### Configure KnpMenuBundle in YAML Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Configure the KnpMenuBundle by defining options in your `config/packages/knp_menu.yaml` file. This example shows disabling Twig support and setting the default renderer. ```yaml # config/packages/knp_menu.yaml knp_menu: # use "twig: false" to disable the Twig extension and the TwigRenderer twig: template: KnpMenuBundle::menu.html.twig # if true, enables the helper for PHP templates # support for templating is deprecated, it will be removed in next major version templating: false # the renderer to use, list is also available by default default_renderer: twig ``` -------------------------------- ### Get a Specific Menu Branch Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Retrieve a specific branch of a menu by providing a path of item keys. The path is an array of strings. ```html+jinja {% set menuItem = knp_menu_get('my_main_menu', ['Contact']) %} {{ knp_menu_render(['my_main_menu', 'Contact']) }} ``` ```html+php get('my_main_menu', ['Contact']) ?> render(['my_main_menu', 'Contact']) ?> ``` -------------------------------- ### Create Menu via Naming Convention Source: https://context7.com/knplabs/knpmenubundle/llms.txt Define a menu by creating a Builder class in your bundle's Menu namespace. Each public method becomes a menu accessible via a 'Bundle:Class:method' string. The method receives the factory and an options array. ```php namespace AppBundle\Menu; use App\Entity\Post; use Doctrine\ORM\EntityManagerInterface; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; final class Builder { public function __construct(private EntityManagerInterface $em) {} public function mainMenu(FactoryInterface $factory, array $options): ItemInterface { $menu = $factory->createItem('root'); $menu->addChild('Home', ['route' => 'homepage']); $latest = $this->em->getRepository(Post::class)->findOneBy([], ['createdAt' => 'DESC']); $menu->addChild('Latest Post', [ 'route' => 'blog_show', 'routeParameters' => ['id' => $latest->getId()], ]); $menu->addChild('About', ['route' => 'about']); $menu['About']->addChild('Edit Profile', ['route' => 'edit_profile']); return $menu; } } ``` -------------------------------- ### Basic Menu Item Creation Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/i18n.rst This snippet shows how to create a basic menu with two items, 'Home' and 'Login', which will be translated by default. ```php $menu = $factory->createItem('root'); $menu->addChild('Home', ['route' => 'homepage']); $menu->addChild('Login', ['route' => 'login']); ``` -------------------------------- ### Render a Menu with Options Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_builder_service.rst Retrieve and render a menu, passing options to its creation method. This allows for dynamic menu generation based on context. ```html+jinja {% set menu = knp_menu_get('sidebar', [], {include_homepage: false}) %} {{ knp_menu_render(menu) }} ``` -------------------------------- ### Configure KnpMenuBundle Source: https://context7.com/knplabs/knpmenubundle/llms.txt Manually configure bundle settings, including Twig template, default renderer, and provider options. Defaults are shown. ```php // config/packages/knp_menu.php $container->loadFromExtension('knp_menu', [ 'twig' => [ 'template' => 'KnpMenuBundle::menu.html.twig', ], 'templating' => false, // PHP templating helper (deprecated) 'default_renderer' => 'twig', // 'twig' or 'list' 'providers' => [ 'builder_alias' => true, // enable/disable the convention-based provider ], ]); ``` -------------------------------- ### Retrieve and Render Full Menu Source: https://context7.com/knplabs/knpmenubundle/llms.txt Fetch an entire menu using `knp_menu_get` and then render it. This allows for inspection or manipulation before rendering. ```twig {# Fetch the whole menu #} {% set menu = knp_menu_get('main') %} {{ knp_menu_render(menu) }} ``` -------------------------------- ### Create Menu as a Service Source: https://context7.com/knplabs/knpmenubundle/llms.txt Register the menu item itself as a service tagged with 'knp_menu.menu'. This approach reuses the same instance and does not support builder options. ```php // src/Menu/MenuBuilder.php namespace App\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\HttpFoundation\RequestStack; class MenuBuilder { public function __construct(private FactoryInterface $factory) {} public function createMainMenu(RequestStack $requestStack): \Knp\Menu\ItemInterface { $menu = $this->factory->createItem('root'); $menu->addChild('Home', ['route' => 'homepage']); $menu->addChild('Login', ['route' => 'login']); return $menu; } } ``` -------------------------------- ### Listen to Custom Menu Configuration Event Source: https://context7.com/knplabs/knpmenubundle/llms.txt Create an event listener that listens for the custom menu configuration event and adds menu items accordingly. This listener should implement the __invoke magic method to handle the event. ```php namespace App\EventListener; use App\Event\ConfigureMenuEvent; class AdminMenuListener { public function __invoke(ConfigureMenuEvent $event): void { $menu = $event->getMenu(); $menu->addChild('Users', ['route' => 'admin_users']); $menu->addChild('Settings', ['route' => 'admin_settings']); } } ``` -------------------------------- ### Retrieve Menu with Builder Options Source: https://context7.com/knplabs/knpmenubundle/llms.txt Fetch a menu using `knp_menu_get` and pass builder options to the menu factory method. The retrieved menu can then be rendered with specific rendering options. ```twig {# Pass builder options to the menu factory method #} {% set sidebar = knp_menu_get('sidebar', [], {include_homepage: true}) %} {{ knp_menu_render(sidebar, {'depth': 1}) }} ``` -------------------------------- ### Register Menu Builder and Main Menu Services Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_service.rst Configure services.yaml to register the menu builder and the main menu. The main menu is defined using a factory method from the builder and tagged with an alias for rendering. ```yaml # config/services.yaml services: app.menu_builder: class: App\Menu\MenuBuilder arguments: ["@knp_menu.factory"] app.main_menu: class: Knp\Menu\MenuItem # the service definition requires setting the class factory: ["@app.menu_builder", createMainMenu] arguments: ["@request_stack"] tags: - { name: knp_menu.menu, alias: main } # The alias is what is used to retrieve the menu # ... ``` -------------------------------- ### Create Menu Builder Service with Attributes Source: https://context7.com/knplabs/knpmenubundle/llms.txt Define a menu builder class with methods annotated by #[AsMenuBuilder] for automatic registration. This is the recommended approach. ```php // src/Menu/MenuBuilder.php namespace App\Menu; use Knp\Menu\Attribute\AsMenuBuilder; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; class MenuBuilder { public function __construct(private FactoryInterface $factory) {} #[AsMenuBuilder(name: 'main')] // referenced as 'main' in templates public function createMainMenu(array $options): ItemInterface { $menu = $this->factory->createItem('root'); $menu->addChild('Home', ['route' => 'homepage']); $menu->addChild('Blog', ['route' => 'blog_index']); $menu->addChild('About', ['route' => 'about']); $menu['About']->addChild('Team', ['route' => 'about_team']); $menu['About']->addChild('Contact', ['route' => 'contact']); return $menu; } #[AsMenuBuilder(name: 'sidebar')] public function createSidebarMenu(array $options): ItemInterface { $menu = $this->factory->createItem('sidebar'); if (!empty($options['include_homepage'])) { $menu->addChild('Home', ['route' => 'homepage']); } $menu->addChild('Recent Posts', ['route' => 'blog_recent']); return $menu; } } ``` -------------------------------- ### Menu Rendering with Options Source: https://context7.com/knplabs/knpmenubundle/llms.txt Control menu rendering by passing an options array to `knp_menu_render`. Options include limiting depth and disabling the current-item link. ```twig {# Render with options: limit depth, disable current-item link #} {{ knp_menu_render('main', {'depth': 2, 'currentAsLink': false}) }} ``` -------------------------------- ### Define a Menu Builder Service Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_builder_service.rst Create a PHP class that implements a menu builder. Use the `#[AsMenuBuilder]` attribute to automatically register it as a service and define the menu's name. ```php namespace App\Menu; use Knp\Menu\Attribute\AsMenuBuilder; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; class MenuBuilder { private $factory; /** * Add any other dependency you need... */ public function __construct(FactoryInterface $factory) { $this->factory = $factory; } #[AsMenuBuilder(name: 'main')] // The name is what is used to retrieve the menu public function createMainMenu(array $options): ItemInterface { $menu = $this->factory->createItem('root'); $menu->addChild('Home', ['route' => 'homepage']); // ... add more children return $menu; } } ``` -------------------------------- ### Implement Custom Menu Provider Source: https://context7.com/knplabs/knpmenubundle/llms.txt Implement the MenuProviderInterface to load menus from custom data sources like databases. Ensure the provider can be found by name and throws an exception if the menu does not exist. ```php namespace App\Provider; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; use Knp\Menu\Provider\MenuProviderInterface; class DatabaseMenuProvider implements MenuProviderInterface { public function __construct(private FactoryInterface $factory) {} public function get(string $name, array $options = []): ItemInterface { if (!$this->has($name, $options)) { throw new \InvalidArgumentException(sprintf('Menu "%s" not found.', $name)); } // Build an ItemInterface tree from your data source $root = $this->factory->createItem($name); // ... populate from DB / PHPCR node / API ... return $root; } public function has(string $name, array $options = []): bool { // Return true if this provider can handle the given name return in_array($name, ['dynamic_nav', 'footer_nav'], true); } } ``` -------------------------------- ### Register Menu Builder Service (YAML) Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_builder_service.rst If autoconfiguration is disabled, manually register the menu builder service and tag it with `knp_menu.menu_builder`, specifying the method and alias. ```yaml # config/services.yaml services: app.menu_builder: class: App\Menu\MenuBuilder arguments: ["@knp_menu.factory"] tags: - { name: knp_menu.menu_builder, method: createMainMenu, alias: main } # The alias is what is used to retrieve the menu # ... ``` -------------------------------- ### Create Menu Builder with Event Dispatch Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/events.rst This PHP code defines a menu builder that creates a base menu and dispatches a 'configure menu' event. Listeners can use this event to add items to the menu. ```php namespace App\Menu; use App\Event\ConfigureMenuEvent; use Knp\Menu\FactoryInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface: class MainBuilder { private $factory; private $eventDispatcher public function __construct(FactoryInterface $factory, EventDispatcherInterface $eventDispatcher) { $this->factory = $factory; $this->eventDispatcher = $eventDispatcher; } public function build(array $options) { $menu = $this->factory->createItem('root'); $menu->addChild('Dashboard', ['route' => '_acp_dashboard']); $this->eventDispatcher->dispatch( new ConfigureMenuEvent($this->factory, $menu), ConfigureMenuEvent::CONFIGURE ); return $menu; } } ``` -------------------------------- ### Basic Menu Rendering Source: https://context7.com/knplabs/knpmenubundle/llms.txt Render a menu by its name using the `knp_menu_render` function. ```twig {# Basic render by name #} {{ knp_menu_render('main') }} ``` -------------------------------- ### Retrieve and Render Specific Menu Branch Source: https://context7.com/knplabs/knpmenubundle/llms.txt Fetch a specific menu branch using `knp_menu_get` with a path array, then render it. ```twig {# Fetch a specific branch #} {% set aboutBranch = knp_menu_get('main', ['About']) %} {{ knp_menu_render(aboutBranch) }} ``` -------------------------------- ### Render Main Menu in Template Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_service.rst Use the knp_menu_render function in your template, passing the alias defined in services.yaml to display the main menu. ```html+jinja {{ knp_menu_render('main') }} ``` -------------------------------- ### Register Custom Renderer Service Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/custom_renderer.rst Define a service for your custom renderer in services.yaml. Ensure the class implements RendererInterface and tag it with 'knp_menu.renderer' using a unique alias. ```yaml services: app.menu_renderer: # The class implements Knp\Menu\Renderer\RendererInterface class: App\Menu\CustomRenderer arguments: ["%kernel.charset%"] # set your own dependencies here tags: # The alias is what is used to retrieve the menu - { name: knp_menu.renderer, alias: custom } # ... ``` -------------------------------- ### Custom Menu Provider Implementation Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/custom_provider.rst Implement the `MenuProviderInterface` to create a custom menu provider. This class should handle the retrieval and construction of menu items based on custom logic, such as fetching data from a repository. ```php namespace App\Provider; use Knp\Menu\FactoryInterface; use Knp\Menu\Provider\MenuProviderInterface; class CustomMenuProvider implements MenuProviderInterface { /** * @var FactoryInterface */ protected $factory = null; /** * @param FactoryInterface $factory the menu factory used to create the menu item */ public function __construct(FactoryInterface $factory) { $this->factory = $factory; } /** * Retrieves a menu by its name * * @param string $name * @param array $options * @return \Knp\Menu\ItemInterface * @throws \InvalidArgumentException if the menu does not exists */ public function get($name, array $options = []) { if ('demo' == $name) { //several menu could call this provider $menu = /* construct / get a \Knp\Menu\NodeInterface */; if ($menu === null) { throw new \InvalidArgumentException(sprintf('The menu "%s" is not defined.', $name)); } /* * Populate your menu here */ $menuItem = $this->factory->createFromNode($menu); return $menuItem; } } /** * Checks whether a menu exists in this provider * * @param string $name * @param array $options * @return bool */ public function has($name, array $options = []) { $menu = /* find the menu called $name */; return $menu !== null; } } ``` -------------------------------- ### Create Event Listener to Add Menu Items Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/events.rst This PHP code defines a listener that adds 'Matches' and 'Participants' menu items. It is invoked when the `ConfigureMenuEvent` is dispatched, allowing dynamic menu item addition. ```php namespace Acme\AdminBundle\EventListener; use App\Event\ConfigureMenuEvent; class ConfigureMenuListener { public function __invoke(ConfigureMenuEvent $event) { $menu = $event->getMenu(); $menu->addChild('Matches', ['route' => 'versus_rankedmatch_acp_matches_index']); $menu->addChild('Participants', ['route' => 'versus_rankedmatch_acp_participants_index']); } } ``` -------------------------------- ### Render a menu using PHP templates Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Render a menu within PHP templates using the `view['knp_menu']->render()` method. Note that templating support is deprecated. ```html+php render('my_main_menu') ?> ``` -------------------------------- ### Register Custom Renderer Extending ListRenderer Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/custom_renderer.rst When extending ListRenderer, provide a Matcher instance and renderer options as arguments. Tag the service with 'knp_menu.renderer' and specify an alias. ```yaml services: app.menu_renderer: # The class implements Knp\Menu\Renderer\RendererInterface class: App\Menu\CustomRenderer arguments: - '@knp_menu.matcher' - '%knp_menu.renderer.list.options%' - '%kernel.charset%' # add your own dependencies here tags: # The alias is what is used to retrieve the menu - { name: knp_menu.renderer, alias: custom } # ... ``` -------------------------------- ### Enable KnpMenuBundle in AppKernel (non-Flex) Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Manually enable the KnpMenuBundle by adding it to your application's Kernel if you are not using Symfony Flex. ```php // e.g. app/AppKernel.php // ... class AppKernel extends Kernel { public function registerBundles() { $bundles = [ // ... new Knp\Bundle\MenuBundle\KnpMenuBundle(), ]; // ... } // ... } ``` -------------------------------- ### Register Menu Item Service Source: https://context7.com/knplabs/knpmenubundle/llms.txt Register the menu item as a service using a factory, linking it to a builder method and tagging it with 'knp_menu.menu'. ```yaml # config/services.yaml services: app.menu_builder: class: App\Menu\MenuBuilder arguments: ["@knp_menu.factory"] app.main_menu: class: Knp\Menu\MenuItem factory: ["@app.menu_builder", createMainMenu] arguments: ["@request_stack"] tags: - { name: knp_menu.menu, alias: main } ``` -------------------------------- ### Register Custom Menu Renderer Source: https://context7.com/knplabs/knpmenubundle/llms.txt Register a custom menu renderer service by implementing RendererInterface or extending ListRenderer, and tagging it with 'knp_menu.renderer' with a unique alias. ```yaml # config/services.yaml services: # Simple custom renderer App\Menu\CustomRenderer: arguments: ["%kernel.charset%"] tags: - { name: knp_menu.renderer, alias: custom } # The service must be public (lazy-loaded at runtime) public: true # Renderer extending ListRenderer (needs a Matcher) App\Menu\BootstrapRenderer: arguments: - '@knp_menu.matcher' - '%knp_menu.renderer.list.options%' - '%kernel.charset%' tags: - { name: knp_menu.renderer, alias: bootstrap } public: true ``` -------------------------------- ### Create Menu Builder Service Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_service.rst Define a menu builder class that utilizes the menu factory to create menu items. This class will be registered as a service. ```php namespace App\Menu; use Knp\Menu\FactoryInterface; use Symfony\Component\HttpFoundation\RequestStack; class MenuBuilder { private $factory; public function __construct(FactoryInterface $factory) { $this->factory = $factory; } public function createMainMenu(RequestStack $requestStack) { $menu = $this->factory->createItem('root'); $menu->addChild('Home', ['route' => 'homepage']); // ... add more children return $menu; } } ``` -------------------------------- ### Render Menu using Bundle:Class:method Source: https://context7.com/knplabs/knpmenubundle/llms.txt Render a menu defined by a Builder class using the three-part 'Bundle:Class:method' string in your Twig template. ```twig {# Render using the three-part bundle:class:method string #} {{ knp_menu_render('App:Builder:mainMenu') }} ``` -------------------------------- ### Service Configuration for Custom Provider Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/custom_provider.rst Configure your custom menu provider as a service in your Symfony application's service configuration file. Ensure it is tagged with `knp_menu.provider` to be recognized by the KnpMenuBundle. ```yaml # config/services.yaml or app/config/services.yml services: app.menu_provider: class: App\Provider\CustomMenuProvider arguments: - '@knp_menu.factory' tags: - { name: knp_menu.provider } # ... ``` -------------------------------- ### Register Custom Menu Provider Source: https://context7.com/knplabs/knpmenubundle/llms.txt Register the custom menu provider service in services.yaml, injecting the menu factory and tagging it with 'knp_menu.provider'. ```yaml # config/services.yaml services: App\Provider\DatabaseMenuProvider: arguments: ['@knp_menu.factory'] tags: - { name: knp_menu.provider } ``` -------------------------------- ### Render Menu with Custom Renderer Source: https://context7.com/knplabs/knpmenubundle/llms.txt Use a custom renderer for your menu by specifying its name as the third argument to `knp_menu_render`. ```twig {# Use a custom renderer #} {{ knp_menu_render('main', {}, 'custom') }} ``` -------------------------------- ### Add a Second Menu Builder Method Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_builder_service.rst Add another method to the existing menu builder class to create a different menu. Use the `#[AsMenuBuilder]` attribute with a unique name. ```php // src/Menu/MenuBuilder.php // ... class MenuBuilder { // ... #[AsMenuBuilder(name: 'sidebar')] public function createSidebarMenu(array $options): ItemInterface { $menu = $this->factory->createItem('sidebar'); if (isset($options['include_homepage']) && $options['include_homepage']) { $menu->addChild('Home', ['route' => 'homepage']); } // ... add more children return $menu; } } ``` -------------------------------- ### Render Specific Menu Branch Source: https://context7.com/knplabs/knpmenubundle/llms.txt Render a specific sub-branch of a menu by providing a path array to `knp_menu_render`. ```twig {# Render a sub-branch (the 'About' child and its descendants) #} {{ knp_menu_render(['main', 'About']) }} ``` -------------------------------- ### Register Event Listener for Menu Configuration Source: https://context7.com/knplabs/knpmenubundle/llms.txt Register the custom event listener in the services.yaml file, tagging it with 'kernel.event_listener' to ensure it's automatically invoked. ```yaml # config/services.yaml services: App\EventListener\AdminMenuListener: tags: [kernel.event_listener] ``` -------------------------------- ### Render a menu with options using Twig Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/index.rst Pass rendering options such as `depth` and `currentAsLink` to the `knp_menu_render` function in Twig templates to customize menu display. ```html+jinja {{ knp_menu_render('my_main_menu', {'depth': 2, 'currentAsLink': false}) }} ``` -------------------------------- ### Register Sidebar Menu Service Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_service.rst Register the new sidebar menu as a service, similar to the main menu, but with a different alias ('sidebar') for distinct rendering. ```yaml # config/services.yaml services: app.sidebar_menu: class: Knp\Menu\MenuItem factory: ["@app.menu_builder", createSidebarMenu] arguments: ["@request_stack"] tags: - { name: knp_menu.menu, alias: sidebar } # Named "sidebar" this time # ... ``` -------------------------------- ### Add Second Menu Method to Builder Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_service.rst Extend the MenuBuilder class by adding a new method to create a different menu, such as a sidebar menu. ```php // ... class MenuBuilder { // ... public function createSidebarMenu(RequestStack $requestStack) { $menu = $this->factory->createItem('sidebar'); $menu->addChild('Home', ['route' => 'homepage']); // ... add more children return $menu; } } ``` -------------------------------- ### Render Sidebar Menu in Template Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/menu_service.rst Render the sidebar menu in a template by calling knp_menu_render with its specific alias, 'sidebar'. ```html+jinja {{ knp_menu_render('sidebar') }} ``` -------------------------------- ### Render Menu from Custom Provider Source: https://context7.com/knplabs/knpmenubundle/llms.txt Render a menu provided by a custom provider using the knp_menu_render Twig function, specifying the menu name. ```twig {{ knp_menu_render('dynamic_nav') }} ``` -------------------------------- ### Define Custom Event Object for Menu Configuration Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/events.rst This PHP code defines a custom event object, `ConfigureMenuEvent`, which carries the menu factory and the menu item being built. It includes constants for event names and getter methods for accessing the data. ```php namespace App\Event; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; use Symfony\Component\EventDispatcher\Event; class ConfigureMenuEvent extends Event { const CONFIGURE = 'app.menu_configure'; private $factory; private $menu; public function __construct(FactoryInterface $factory, ItemInterface $menu) { $this->factory = $factory; $this->menu = $menu; } /** * @return \Knp\Menu\FactoryInterface */ public function getFactory() { return $this->factory; } /** * @return \Knp\Menu\ItemInterface */ public function getMenu() { return $this->menu; } } ``` -------------------------------- ### Register Event Listener Service Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/events.rst This YAML configuration registers the `ConfigureMenuListener` as a service tagged with `kernel.event_listener`. This ensures the listener is automatically called when the relevant event is dispatched. ```yaml services: app.admin_configure_menu_listener: class: Acme\AdminBundle\EventListener\ConfigureMenuListener tags: [kernel.event_listener] ``` -------------------------------- ### Use Custom Menu Renderer Source: https://context7.com/knplabs/knpmenubundle/llms.txt Use a custom menu renderer in a Twig template by passing the renderer's alias as the third argument to the knp_menu_render function. ```twig {# Use the custom renderer by passing its alias as the third argument #} {{ knp_menu_render('main', {'depth': 2}, 'bootstrap') }} ``` -------------------------------- ### Pass Translation Parameters Source: https://context7.com/knplabs/knpmenubundle/llms.txt Pass parameters to the translation system for menu item labels by using the `translation_params` extra. This allows for dynamic content in translated strings. ```php // Pass translation parameters $menu->addChild('greeting', ['route' => 'home']) ->setExtra('translation_params', ['%name%' => 'World']); ``` -------------------------------- ### Rendering a Menu in Twig Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/custom_provider.rst Render a menu registered with a custom provider in your Twig templates using the `knp_menu_render` function, passing the name of the menu you wish to display. ```html+jinja {{ knp_menu_render('demo') }} ``` -------------------------------- ### Dispatch Custom Menu Configuration Event Source: https://context7.com/knplabs/knpmenubundle/llms.txt In a menu builder, dispatch a custom event to allow external listeners to add menu items. This involves injecting an EventDispatcherInterface and dispatching a new instance of the custom event. ```php namespace App\Menu; use App\Event\ConfigureMenuEvent; use Knp\Menu\FactoryInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class MainBuilder { public function __construct( private FactoryInterface $factory, private EventDispatcherInterface $dispatcher ) {} public function build(array $options): \Knp\Menu\ItemInterface { $menu = $this->factory->createItem('root'); $menu->addChild('Dashboard', ['route' => '_dashboard']); // Other bundles/services can add items here $this->dispatcher->dispatch( new ConfigureMenuEvent($this->factory, $menu), ConfigureMenuEvent::CONFIGURE ); return $menu; } } ``` -------------------------------- ### Configure Translation Domain Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/i18n.rst This snippet demonstrates how to configure a specific translation domain for a menu item using the 'translation_domain' extra. ```php // ... $menu->addChild('Home', ['route' => 'homepage']) ->setExtra('translation_domain', 'AcmeAdminBundle'); ``` -------------------------------- ### Render Menu with Custom Renderer in Twig Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/custom_renderer.rst Use the knp_menu_render Twig function to render a menu, specifying the menu name, options, and the alias of your custom renderer. ```twig {{ knp_menu_render('main', {}, 'custom') }} ``` -------------------------------- ### Define Custom Event for Menu Configuration Source: https://context7.com/knplabs/knpmenubundle/llms.txt Define a custom event class to allow other parts of the application to hook into menu building. This requires extending Symfony's Event class and providing methods to access the menu factory and item. ```php namespace App\Event; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; use Symfony\Contracts\EventDispatcher\Event; class ConfigureMenuEvent extends Event { const CONFIGURE = 'app.menu_configure'; public function __construct( private FactoryInterface $factory, private ItemInterface $menu ) {} public function getFactory(): FactoryInterface { return $this->factory; } public function getMenu(): ItemInterface { return $this->menu; } } ``` -------------------------------- ### Disable Built-in Menu Providers Source: https://context7.com/knplabs/knpmenubundle/llms.txt Disable specific built-in menu providers in the knp_menu.yaml configuration file by setting their respective keys to false to optimize performance when only a single provider is needed. ```yaml # config/packages/knp_menu.yaml knp_menu: providers: builder_alias: false # disable the Bundle:Class:method convention provider ``` -------------------------------- ### Translate Menu Labels with Default Domain Source: https://context7.com/knplabs/knpmenubundle/llms.txt Menu item labels are translated automatically using the 'messages' domain. Ensure the corresponding key exists in your translation files (e.g., `translations/messages.fr.yaml`). ```php // src/Menu/MenuBuilder.php $menu = $this->factory->createItem('root'); // Uses default 'messages' domain — add 'Home' key to translations/messages.fr.yaml $menu->addChild('Home', ['route' => 'homepage']); ``` -------------------------------- ### Configure Custom Twig Template in YAML Source: https://context7.com/knplabs/knpmenubundle/llms.txt Specify a custom Twig template for KnpMenuBundle rendering in your Symfony application's configuration. This tells the bundle to use your overridden template instead of the default. ```yaml # config/packages/knp_menu.yaml knp_menu: twig: template: 'menu/custom_menu.html.twig' ``` -------------------------------- ### Disable Builder Alias Provider Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/disabling_providers.rst Disable the builder-alias-based provider by setting its configuration to false. All providers are enabled by default. ```yaml knp_menu: providers: builder_alias: false # disable the builder-alias-based provider ``` -------------------------------- ### Override Translation Domain per Item Source: https://context7.com/knplabs/knpmenubundle/llms.txt Set a specific translation domain for a menu item using the `translation_domain` extra. This allows using different translation files for different menu items. ```php // Override the translation domain per item $menu->addChild('Dashboard', ['route' => 'dashboard']) ->setExtra('translation_domain', 'admin'); ``` -------------------------------- ### Override Menu Label Block in Twig Source: https://context7.com/knplabs/knpmenubundle/llms.txt Extend the default KnpMenuBundle template and override the 'label' block to customize how menu item labels are rendered, including translation and safe HTML handling. This is useful for global label customization. ```twig {# templates/menu/custom_menu.html.twig #} {% extends 'knp_menu.html.twig' %} {% block label %} {%- set domain = item.extra('translation_domain', 'messages') -%} {%- set label = item.label -%} {%- if domain is not same as(false) -%} {%- set label = label|trans(item.extra('translation_params', {}), domain) -%} {%- endif -%} {%- if options.allow_safe_labels and item.extra('safe_label', false) -%} {{ label|raw }} {%- else -%} {{ label }} {%- endif -%} {% endblock %} ``` -------------------------------- ### Disable Menu Item Translation Source: https://github.com/knplabs/knpmenubundle/blob/master/docs/i18n.rst This snippet shows how to disable the translation for a menu item by setting its 'translation_domain' extra to false. ```php $menu->addChild('About', ['route' => 'about']) ->setExtra('translation_domain', false); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.