Search code examples
symfonyknpmenubundleknpmenusymfony5

Symfony 5.0 and KnpMenuBundle - how to configure


In a Symfony 5.0 Application I want to use the KnpMenuBundle. I installed it by running

composer require knplabs/knp-menu-bundle "^3.0"

This automatically created an entry in [ProjectRoot]/config/bundles.php":

Knp\Bundle\MenuBundle\KnpMenuBundle::class => ['all' => true]

Of course it downloaded the bundle as well.

The documentation (found at: https://symfony.com/doc/master/bundles/KnpMenuBundle/index.html) states to configure the bundle one should edit the file "app/config/config.yml". Symfony 5 does not have this file anymore - but single config files for each "package" in "[ProjectRoot]/config/packages". However there wasn't a config file created for KnpMenuBundle. How could I do this myself - meaning: Whats the naming conventions and how do I tell the bundle to actualy use the config file?

There is another issue. In the documentation it says rendering a Menu in a twig template works like this:

{{ knp_menu_render('AppBundle:Builder:mainMenu') }}

For Symfony 5 - what would be the right syntax / path there?


Solution

  • Configuration for KnpMenuBundle is optional. That is why there is no configuration file created. In Symfony 4 and 5 you can just add a yaml config file in the config/packages directory manually. It will be automatically read. A good name for this file could be knp_menu.yaml. Inside the config file you use the same content as documented. e.g.

    knp_menu:
        twig:
            template: KnpMenuBundle::menu.html.twig
    

    To render the menu you can use

    {{ knp_menu_render('App:Builder:mainMenu') }}
    

    Where Builder is the name of the class inside the src/Menu directory and mainMenu is method to call from the class (See the docs).

    UPDATE

    If i am not wrong you have to define the Builder class as a service from Symfony 4 which is slightly different. As you can read from the docs you will now render your menu giving the alias of the service e.g.

    {{ knp_menu_render('main') }}
    

    (Change all AppBundle occurrences to App).