Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Bundles
  4. KnpMenuBundle
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Installation
    • Step 1: Download the Bundle
    • Step 2: Enable the Bundle
    • Step 3: (optional) Configure the bundle
  • Create your first menu!
    • Method a) The Easy Way (yay)!
    • Method b) A menu builder as a service
    • Method c) A menu as a service
  • Rendering Menus
  • More Advanced Stuff

Using KnpMenuBundle

Edit this page

Using KnpMenuBundle

Welcome to KnpMenuBundle - creating menus is fun again!

Installation

Step 1: Download the Bundle

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:

1
$ composer require knplabs/knp-menu-bundle

This command requires you to have Composer installed globally, as explained in the installation chapter of the Composer documentation.

Step 2: Enable the Bundle

KnpMenuBundle should be automatically enabled and configured, thanks to Flex.

If you don't use Flex, you can manually enable it, by adding the following line in your project's Kernel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// e.g. app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            // ...

            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
        ];

        // ...
    }

    // ...
}

Step 3: (optional) Configure the bundle

The bundle comes with a sensible default configuration, which is listed below. You can define these options if you need to change them:

1
2
3
4
5
6
7
8
9
# 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
    templating: false
    # the renderer to use, list is also available by default
    default_renderer: twig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- config/packages/knp_menu.xml -->
<?xml version="1.0" charset="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:knp-menu="http://knplabs.com/schema/dic/menu">

    <!--
        templating:       if true, enabled the helper for PHP templates
        default-renderer: the renderer to use, list is also available by default
    -->
    <knp-menu:config
        templating="false"
        default-renderer="twig"
    >
        <!-- add enabled="false" to disable the Twig extension and the TwigRenderer -->
        <knp-menu:twig template="KnpMenuBundle::menu.html.twig"/>
    </knp-menu:config>
</container>
1
2
3
4
5
6
7
8
9
10
11
// 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, enabled the helper for PHP templates
    'templating' => false,
    // the renderer to use, list is also available by default
    'default_renderer' => 'twig',
]);

Note

Take care to change the default renderer if you disable the Twig support.

Create your first menu!

There are two ways to create a menu: the "easy" way, and the more flexible method of creating a menu as a service.

Method a) The Easy Way (yay)!

To create a menu, first create a new class in the Menu directory of one of your bundles. This class - called Builder in our example - will have one method for each menu that you need to build.

An example builder class would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// src/Menu/Builder.php
namespace App\Menu;

use App\Entity\Blog;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

final class Builder implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function mainMenu(FactoryInterface $factory, array $options): ItemInterface
    {
        $menu = $factory->createItem('root');

        $menu->addChild('Home', ['route' => 'homepage']);

        // access services from the container!
        $em = $this->container->get('doctrine')->getManager();
        // findMostRecent and Blog are just imaginary examples
        $blog = $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;
    }
}

With the standard knp_menu.html.twig template and your current page being 'Home', your menu would render with the following markup:

1
2
3
4
5
6
7
8
9
10
11
12
13
<ul>
    <li class="current first">
        <a href="#route_to/homepage">Home</a>
    </li>
    <li class="current_ancestor">
        <a href="#route_to/page_show/?id=42">About Me</a>
        <ul class="menu_level_1">
            <li class="current first last">
                <a href="#route_to/edit_profile">Edit profile</a>
            </li>
        </ul>
    </li>
</ul>

Note

You only need to implement ContainerAwareInterface if you need the service container. The more elegant way to handle your dependencies is to inject them in the constructor. If you want to do that, see the method below.

Note

The menu builder can be overwritten using the bundle inheritance.

To actually render the menu, just do the following from anywhere in any template:

1
{{ knp_menu_render('App:Builder:mainMenu') }}
1
<?php echo $view['knp_menu']->render('App:Builder:mainMenu') ?>

With this method, you refer to the menu using a three-part string: bundle:class:method.

If you needed to create a second menu, you'd simply add another method to the Builder class (e.g. sidebarMenu), build and return the new menu, then render it via App:Builder:sidebarMenu.

That's it! The menu is very configurable. For more details, see the KnpMenu documentation.

Method b) A menu builder as a service

For information on how to register a menu builder as a service, read Creating Menu Builders as Services.

Method c) A menu as a service

For information on how to register a service and tag it as a menu, read Creating Menus as Services.

Note

To improve performances, you can disable providers you don't need.

Rendering Menus

Once you've set up your menu, rendering it is easy. If you've used the "easy" way, then do the following:

1
{{ knp_menu_render('App:Builder:mainMenu') }}
1
<?php echo $view['knp_menu']->render('App:Builder:mainMenu') ?>

Additionally, you can pass some options to the renderer:

1
{{ knp_menu_render('App:Builder:mainMenu', {'depth': 2, 'currentAsLink': false}) }}
1
2
3
4
<?php echo $view['knp_menu']->render('App:Builder:mainMenu', [
    'depth'         => 2,
    'currentAsLink' => false,
]) ?>

For a full list of options, see the "Other rendering options" header on the KnpMenu documentation.

You can also "get" a menu, which you can use to render later:

1
2
{% set menuItem = knp_menu_get('App:Builder:mainMenu') %}
{{ knp_menu_render(menuItem) }}
1
2
<?php $menuItem = $view['knp_menu']->get('App:Builder:mainMenu') ?>
<?php echo $view['knp_menu']->render($menuItem) ?>

If you want to only retrieve a certain branch of the menu, you can do the following, where 'Contact' is one of the root menu items and has children beneath it.

1
2
{% set menuItem = knp_menu_get('App:Builder:mainMenu', ['Contact']) %}
{{ knp_menu_render(['App:Builder:mainMenu', 'Contact']) }}
1
2
<?php $menuItem = $view['knp_menu']->get('App:Builder:mainMenu', ['Contact']) ?>
<?php echo $view['knp_menu']->render(['App:Builder:mainMenu', 'Contact']) ?>

If you want to pass some options to the builder, you can use the third parameter of the knp_menu_get function:

1
2
{% set menuItem = knp_menu_get('App:Builder:mainMenu', [], {'some_option': 'my_value'}) %}
{{ knp_menu_render(menuItem) }}
1
2
3
4
<?php $menuItem = $view['knp_menu']->get('App:Builder:mainMenu', [], [
    'some_option' => 'my_value'
]) ?>
<?php echo $view['knp_menu']->render($menuItem) ?>

More Advanced Stuff

  • Creating Menus as Services
  • Creating Menu Builders as Services
  • I18n for your Menu Labels
  • Using events to allow a menu to be extended
  • Registering your own renderer
  • Registering your own provider
  • Disabling the Core Menu Providers
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Peruse our complete Symfony & PHP solutions catalog for your web development needs.

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Rémy Vuong, a Symfony contributor

    Thanks Rémy Vuong (@rvuong) for being a Symfony contributor

    1 commit • 2 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia