Search code examples
symfonyknpmenubundle

Several knp menu templates in symfony 3


Is there a way to use several menu templates, instead of the one in vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views/knp_menu.html.twig

Or set template name right in Builder for certain menu (using the example in http://symfony.com/doc/current/bundles/KnpMenuBundle/index.html)?


Solution

  • If in knp_menu_render function we will call template AppBundle:Menu:knp_menu.html.twig then move demo menu file to src/AppBundle/Resources/views/Menu/knp_menu.html.twig like here in docs: http://symfony.com/doc/current/book/templating.html#template-naming-and-locations

    By steps:

    In the template write:

    {{ knp_menu_render('AppBundle:Builder:mainMenu', 'template': 'AppBundle:Menu:knp_menu.html.twig'}) }}
    

    copy file:

    cp vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views/knp_menu.html.twig src/AppBundle/Resources/views/Menu/knp_menu.html.twig
    

    Example of src/AppBundle/Menu/Builder.php

    <?php
    namespace AppBundle\Menu;
    
    use Knp\Menu\FactoryInterface;
    use Symfony\Component\DependencyInjection\ContainerAwareInterface;
    use Symfony\Component\DependencyInjection\ContainerAwareTrait;
    
    class Builder implements ContainerAwareInterface
    {
        use ContainerAwareTrait;
    
        public function mainMenu(FactoryInterface $factory, array $options)
        {
            $menu = $factory->createItem('root');
    
            $menu->addChild('Main', array('route' => 'homepage'));
            $menu->setChildrenAttribute('class', 'nav navbar-nav');
    
            // create another menu item
            $menu->addChild('About', array('route' => 'About'));
            $menu['About']->addChild('Contacts', array('route' => 'About'));
            $menu['About']->addChild('Contacts1', array('route' => 'About'));
            $menu['About']->setChildrenAttribute('class', 'dropdown-menu');
            // ... add more children
    
            return $menu;
        }
    }