converia/config-knp-menu-bundle
Installation:
composer require jbouzekri/config-knp-menu-bundle
Enable the bundle in config/bundles.php (or AppKernel.php for older Laravel versions):
return [
// ...
Jb\Bundle\ConfigKnpMenuBundle\JbConfigKnpMenuBundle::class => ['all' => true],
Knp\Bundle\MenuBundle\KnpMenuBundle::class => ['all' => true],
];
Create a navigation.yml:
Place this file in Resources/config/navigation.yml within your bundle (e.g., src/MyBundle/Resources/config/navigation.yml).
Example:
menu.main:
children:
- label: 'Home'
route: home
- label: 'About'
route: about
First Use Case: Use the menu in a Twig template:
{{ knp_menu('menu.main') }}
Ensure KnpMenuBundle is registered in your Twig environment (handled automatically by the bundle).
Bundle-Specific Menus:
Define menus per bundle in Resources/config/navigation.yml. Example for an AdminBundle:
menu.admin:
children:
- label: 'Users'
route: admin_user_index
- label: 'Settings'
route: admin_settings
Dynamic Menu Items: Use PHP callbacks in YAML for dynamic logic:
menu.dashboard:
children:
- label: 'Notifications'
route: dashboard_notifications
display: {{ app.hasUnreadNotifications() ? true : false }}
Inheritance & Overrides: Extend parent menus in child bundles by redefining the same key. Example:
menu.main:
children:
- label: 'Home'
route: home
- label: 'Extended Menu'
route: extended_route
Integration with Controllers: Pass menu names dynamically:
return $this->render('template.html.twig', [
'menu' => 'menu.' . $this->getUser()->getRole()
]);
Localization: Use translation placeholders for labels:
menu.main:
children:
- label: '{{ "home"|trans }}'
route: home
YAML Syntax Errors:
Menu Registration Timing:
navigation.yml must be loaded before the Twig template renders. If the menu appears empty, check:
bundles.php.navigation.yml file exists in the correct path (Resources/config/).menu.main vs. menu_main).Route Resolution:
route: home) are defined in your config/routes.yaml or bundle routes.route: 'app_home') for clarity.Caching:
php bin/console cache:clear
config/packages/knp_menu.yaml for development:
knp_menu:
twig:
template: knp_menu.html.twig
caching: false
Debugging:
{{ dump(knp_menu('menu.main').children) }}
Configuration Quirks:
true/false (not yes/no) in YAML for attributes like display.children for submenus and subchildren for deeper nesting (if supported by KnpMenuBundle).Extension Points:
MenuBuilder service to add logic:
# config/services.yaml
services:
App\Menu\CustomMenuBuilder:
tags: [knp_menu.menu_builder]
knp_menu.html.twig) in your bundle’s templates/ directory.Performance:
provider:
menu.large:
provider: App\Menu\LargeMenuProvider
Knp\Menu\MenuItemInterface in your provider to fetch items dynamically.Testing:
$menu = $this->get('knp_menu.factory')->createItem('root');
$this->get('knp_menu.renderer.twig')->render($menu);
How can I help you explore Laravel packages today?