Menu Library for PHP

Related tags

Laravel php menu


The KnpMenu library provides object oriented menus for PHP. It is used by the KnpMenuBundle for Symfony but can now be used stand-alone.

Build Status Latest Stable Version Latest Unstable Version Gitter chat


KnpMenu uses Composer, please checkout the composer website for more information.

The simple following command will install knp-menu into your project. It also add a new entry in your composer.json and update the composer.lock as well.

$ composer require knplabs/knp-menu

KnpMenu follows the PSR-4 convention names for its classes, which means you can easily integrate knp-menu classes loading in your own autoloader.

Getting Started


// Include dependencies installed with composer
require 'vendor/autoload.php';

use Knp\Menu\MenuFactory;
use Knp\Menu\Renderer\ListRenderer;

$factory = new MenuFactory();
$menu = $factory->createItem('My menu');
$menu->addChild('Home', ['uri' => '/']);
$menu->addChild('Comments', ['uri' => '#comments']);
$menu->addChild('Symfony', ['uri' => '']);
$menu->addChild('Happy Awesome Developers');

$renderer = new ListRenderer(new \Knp\Menu\Matcher\Matcher());
echo $renderer->render($menu);

The above menu would render the following HTML:

  <li class="first">
    <a href="/">Home</a>
  <li class="current">
    <a href="#comments">Comments</a>
    <a href="">Symfony</a>
  <li class="last">
    <span>Happy Awesome Developers</span>

This way you can finally avoid writing an ugly template to show the selected item, the first and last items, submenus, ...

The bulk of the documentation can be found in the doc directory.

What now?

Follow the tutorial in doc/ and doc/ to discover how KnpMenu will rock your world!

Find all available documentation at doc/.


This library is maintained by the following people (alphabetically sorted) :


This bundle was originally ported from ioMenuPlugin, a menu plugin for symfony1. It has since been developed by KnpLabs and the Symfony community.

  • [WIP] [Outdated] Added a first implementation of a BreadcrumbRenderer

    [WIP] [Outdated] Added a first implementation of a BreadcrumbRenderer

    This is a WIP about #24 meant for discussion.

    This implementation uses the getBreadcrumbsArray method, making it easy to append additional stuff at the end of the breadcrumb. However, it means that you are limited when rendering each item as you only have the label and the uri. The other solution would be to build an array of items or to call getParent each time, but it would make it harder to pass additional paths as it would require building items for them (in this regards, an array of items would be easier than calling getParent during the rendering though as we don't need to add the new items in the existing menu tree).

    To use it, you need to call the knp_menu_render method with the item corresponding to the end of the breadcrumbs, i.e. the item for which the breadcrumb is rendered (except the additional path of course). This is a good use case to get an item by path in the tree

    opened by stof 48
  • Improving the way the current item is determined

    Improving the way the current item is determined

    Currently, the library still uses the behavior coming from KnpMenuBundle:

    • an item can be set explicitly as being (or not being) current.
    • if the flag is not set, the uri is checked against the current uri set for the item (and if there is no current uri, it is not a current item)

    There is some improvements needed here:

    • there can be multiple current items in a tree so the getCurrentItem method is lying by giving only the first found (should it be removed entirely ?)
    • this part of the library should be more flexible to support other behaviors (for instance matching several uris on the same item)
    Improvement RFC 
    opened by stof 40
  • Displaying menu for a certain level in the tree

    Displaying menu for a certain level in the tree

    No matter what level the current page is, I am displaying all the level 1 items across the top of the page, then all the level 2 items in a separate LHS col menu.

    This doesn't seem to be straight forward as there is no helper to render a menu at a certain level, and no means to easily return e.g. the level 2 ancestor for the current page, in order to use this to create the menu.

    Currently in order to achieve this, I am working up the provided breadCrumb array and testing for the level at each point, only rendering the LHS menu when I find the ancestor with the required level.

    This is really messy in twig... clearly not the right way to go about it.

    So I am wondering about whether to add methods to the menuItems class to return information regarding ancestors.

    e.g. would it be useful to have

     * @param int $level     The level of the ancestor to be returned
     * @return \Knp\Menu\ItemInterface
    public function getAncestor($level)

    Any thoughts?

    Is there already an accepted way to do this kind of thing?

    opened by petesiss 33
  • How to use menus in Symfony 4

    How to use menus in Symfony 4

    Before the bundlle system deprecation, I used to do this:

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

    But now that AppBundle doesn't exist anymore, how can I render the menu?

    Obviously this syntax doesn't work...

    opened by Aerendir 27
  • Removing the getCurrentItem method

    Removing the getCurrentItem method

    I open this issue to separate the discussion about this point as I originally asked in #2 but it got a bit lost in the other part of the issue.

    As mentioned previously in #2, this method is currently lying as it returns the first current item found whereas the tree could contain several item. So I see 3 solutions:

    1. Forbid to have more than 1 current item. This would be quite hard to do in an efficient way and most people commenting on it previously thought it is valid to have several one.
    2. Remove the method
    3. Replace the method by a getCurrentItems method. This method would return an array containing all current items inside the tree of the item.

    I personally think that the third option is not necessary. Implementing it using some PHP iterators would be probably more efficient as we would loop over the whole tree only when actually looping over the data instead of doing it first to create the array (and for people wanting an array absolutely, they could still use iterator_to_array).

    So my personal vote would be 2

    opened by stof 23
  • add phpstan

    add phpstan

    This is a first try to add phpstan. ~~Level is 6 for now, maybe we could increase it eventually. I'm not really happy with baseline, so I'm open to suggestion about it~~

    opened by garak 18
  • Add new 'knp_menu_get_current_item' Twig function

    Add new 'knp_menu_get_current_item' Twig function

    The source Gist:

    This PR add a new knp_menu_get_current_item(menu) Twig function which returns the current item of the menu provided as argument.

    For example, this new Twig function can be used with the knp_menu_get_breadcrumbs_array Twig function to easily display the breadcrumb of the current page:

    <ol class="breadcrumb">
    {% for breadcrumb_item in knp_menu_get_breadcrumbs_array(knp_menu_get_current_item('main')) %}
        {% if not loop.last %}
        <li><a href="{{ breadcrumb_item.uri }}">{{ breadcrumb_item.label }}</a></li>
        {% else %}
        <li class="active">{{ breadcrumb_item.label }}</li>
        {% endif %}
    {% endfor %}
    opened by fsevestre 18
  • What is missing for 2.1?

    What is missing for 2.1?


    The CMF project is working hard towards a new release, including support for KnpMenu(Bundle) 2. However, we missed lots of templating functions which were added by #189. This one is not yet included in a release and will be included in the 2.1 release. ( needs to be merged as well)

    We wonder if there is anything we can help with to make the 2.1 release a thing. Can you maybe create a list of issues/PRs that should be finished/fixed before you think a 2.1 release is ready? This way, we can help you preparing the release, as it's currently a big blocker for the next CMF release (releasing without KnpMenu 2 support isn't a option because of Sonata).

    /cc @dbu @lsmith77

    opened by wouterj 16
  • where is setCurrentUri?

    where is setCurrentUri?

    Fatal error: Call to undefined method Knp\Menu\MenuItem::setCurrentUri()

    I can't find this method anymore. Something changed? Documentation says nothing. Or am I terribly wrong?

    opened by iJanki 15
  • Adding support for `weight` item option.

    Adding support for `weight` item option.

    See #97.


    $factory = new MenuFactory();
    $menu = $factory->createItem('My menu');
    $menu->addChild('Home', array('uri' => '/', array('extras' => array('weight' => 10))));
    $menu->addChild('Comments', array('uri' => '#comments'));
    $menu->addChild('Symfony2', array('uri' => ''));
    $menu->addChild('Coming soon', array('extras' => array('weight' => 10))));
    $renderer = new SortingRenderer(new ListRenderer(new \Knp\Menu\Matcher\Matcher()), new MenuManipulator());
    echo $renderer->render($menu);
    opened by akerouanton 14
  • Integrated more functions into Twig

    Integrated more functions into Twig

    Now some functions are moved from ItemInterface to utils and other classes, there is no way they can be used inside a template.

    This PR adds back some functionality.

    As we need this to finish our KnpMenu 2.0 update for the Symfony CMF project, can this please be reviewed and merged quickly and be included in a new minor version?

    opened by wouterj 14
  • Fix phpstan issue

    Fix phpstan issue

    Currently when creating a RecursiveItemIterator passing a new ArrayIterator, the Iterator is indexed by int.

    $treeIterator = new \RecursiveIteratorIterator(
                new RecursiveItemIterator(
                    new \ArrayIterator(array($menu))
                ), \RecursiveIteratorIterator::SELF_FIRST

    So we got the following error:

    Parameter #1 $iterator of class Knp\Menu\Iterator\RecursiveItemIterator constructor expects
    Traversable<string, Knp\Menu\ItemInterface>, ArrayIterator<int, Knp\Menu\ItemInterface> given.

    I can notice that the typehint in CurrentItemFilterIterator is ok:

    Waiting for user's input 
    opened by raziel057 1
  • Suggesting some configurations

    Suggesting some configurations

    Most common thing to do after utilising KnpMenu, is overriding the template, I believe we can overcome this step by providing some config in a yaml file for example

      menu_class: 'navbar-nav me-auto mb-2 mb-lg-0'
      menu_item_class: 'nav-item'
      menu_item_link_class: 'nav-link'
      current_class: 'active'
      current_class_on_link: true  

    I'd be willing to put some time in this effort with some direction, I lack the confidence in providing a solution like this :)

    opened by alexseif 0
  • setChildren properly sets the parent on children

    setChildren properly sets the parent on children

    Children items sets by \Knp\Menu\MenuItem::setChildren setter does not have parent properly set. This issue does not occur in \Knp\Menu\MenuItem::addChild.

    Waiting for user's input 
    opened by damianz5 1
  • Add template for boostrap 4 etc.?

    Add template for boostrap 4 etc.?

    In every project I use this library, I find myself adding a template of mine to render with Bootstrap 4. I think it could nice to provide here templates for major CSS vendors (Bootstrap, Foundation, etc.), just like Symfony is doing for its form themes.

    Improvement RFC 
    opened by garak 3
  • Label with hierarchical numbering

    Label with hierarchical numbering

    I am using the ListRenderer to create a table of contents for a webpage (actually I use and th OrderedListRenderer).

    Using some CSS pseudo elements, I am able to get hierarical numbering dynamically:

    		ol {
    			list-style-type: none;
    			counter-reset: item;
    			margin: 0;
    			padding: 0;
    		ol > li {
    			display: table;
    			counter-increment: item;
    			margin-bottom: 0.6em;
    		ol > li:before {
    			content: counters(item, ".") ". ";
    			display: table-cell;
    			padding-right: 0.6em;
    		li ol > li {
    			margin: 0;
    		li ol > li:before {
    			content: counters(item, ".") " ";

    Gives something like: image

    But would it be possible to compute and render these "addresses" and set them as value attribute in the created list? Like here

    <li value="2.1">Übersicht</li>

    Thanks in advance! Stay healty!

    opened by flaushi 0
  • v3.3.0(Oct 28, 2021)

  • v3.2.0(May 28, 2021)

  • v3.1.2(Aug 15, 2020)

  • v3.1.1(Apr 22, 2020)

  • v3.1.0(Dec 1, 2019)

  • v3.0.0(Sep 2, 2019)

    • Raised PHP requirements. This library now requires PHP 7.2 or newer
    • [BC break] Enforced strong types on all interfaces and classes. If you implemented library interface, you need to adapt your implementations.
    • [BC break] Removed all features deprecated in version 2. Specifically, MenuFactory and MenuItem are not accepting a null name anymore
    Source code(tar.gz)
    Source code(zip)
  • 2.5.0(Aug 23, 2019)

  • 2.4.0(Jul 29, 2019)

    • fixed Twig deprecations
    • switched to namespaced Twig
    • fixed sprintf use
    Source code(tar.gz)
    Source code(zip)
  • 2.3.0(Nov 29, 2017)

    New features

    • Added Symfony 4 support
    • Added a new LazyProvider for menus, building menus from callables or "callable builders"
    • Added support for injecting the RequestStack in the RouteVoter
    • Added support for iterable in the ChainProvider (allowing lazy-loading of providers in the iterator)
    • Added support for menu and renderer providers based on a PSR-11 container
    • Added support for registering voters using an iterator

    Bug fixes

    • Fixed RouteVoter to also match on non-string request arguments like integers as long as both string representations are identical.
    • Fixed support for the depth ancestor of the knp_menu_ancestor Twig test


    • Deprecated the Silex 1 KnpMenuServiceProvider. Use the knplabs/knp-menu-silex package instead.
    • Injecting a Request in the RouteVoter is deprecated. Inject the RequestStack instead.
    • Deprecated MenuMatcher::addVoter. Inject voters in the constructor instead
    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Sep 22, 2016)

  • v2.1.0(Sep 20, 2015)

    • Added a new function to twig: knp_menu_get_breadcrumbs_array
    • Added a new filter to twig: knp_menu_as_string
    • Added 2 new tests to twig: knp_menu_current, knp_menu_ancestor
    • Made the templates compatible with Twig 2
    • Add menu and renderer providers supporting any ArrayAccess implementations. The Pimple-based providers (supporting only Pimple 1) are dperecated in favor of these new providers.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Aug 1, 2014)

  • v2.0.0(Jul 18, 2014)

  • v2.0.0-beta1(Jun 20, 2014)

    • [BC break] Added the new Integration namespace and removed the Silex one.
    • Added a new Voter based on regular expression: Knp\Menu\Matcher\Voter\RegexVoter
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-alpha2(Jun 20, 2014)

    • [BC break] Changed the TwigRenderer to accept a menu template only as a string

    • [BC break] Refactored the way of rendering twig templates. Every template should extends the knp_menu.html.twig template.

    • Introduced extension points in the MenuFactory through Knp\Menu\Factory\ExtensionInterface

    • [BC break compared to 2.0 alpha 1] The inheritance extension points introduced in alpha1 are deprecated in favor of extensions and will be removed before the stable release.

    • Knp\Menu\Silex\RouterAwareFactory is deprecated in favor of Knp\Menu\Silex\RoutingExtension.

    • [BC break] Deprecated the methods createFromArray and createFromNode in the MenuFactory and removed them from Knp\Menu\FactoryInterface. Use Knp\Menu\Loader\ArrayLoader and Knp\Menu\Loader\NodeLoader instead.

    • [BC break] Deprecated the methods moveToPosition, moveToFirstPosition, moveToLastPosition, moveChildToPosition, callRecursively, toArray, getPathAsString and getBreadcrumbsArray in the MenuItem and removed them from Knp\Menu\ItemInterface. Use Knp\Menu\Util\MenuManipulator instead.

    • Made the RouterVoter compatible with SensioFrameworkExtraBundle param converters

    • Added the possibility to match routes using a regex on their name in the RouterVoter

    • [BC break compared to 2.0 alpha 1] Refactored the RouterVoter to make it more flexible The way to pass routes in the item extras has changed.


      'extras' => array(
          'routes' => array('foo', 'bar'),
          'routeParameters' => array('foo' => array('id' => 4)),


      'extras' => array(
          'routes' => array(
               array('route' => 'foo', 'parameters' => array('id' => 4)),

      The old syntax is kept until the final release, but using it will trigger a E_USER_DEPRECATED error.

    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-alpha1(Jul 3, 2013)

    This alpha release does not represent the final feature set of 2.0. As the development of 2.0 hanged for a while, many people are already using the current state of the code so this alpha release allows them to lock it if they cannot update for the new changes.


    • Added protected methods buildOptions and configureItem in the MenuFactory as extension point by inheritance
    • [BC break] Refactored the way to mark items as current setCurrentUri, getCurrentUri and getCurrentItem have been removed from the ItemInterface. Determining the current items is now delegated to a matcher, and the default implementation uses voters to apply the matching. Getting the current items can be done thanks to the CurrentItemFilterIterator.
    • [BC break] The signature of the CurrentItemFilterIterator constructor changed to accept the item matcher
    • [BC break] Changed the format of the breadcrumb array Instead of storing the elements with the label as key and the uri as value the array now stores an array of array elements with 3 keys: label, uri and item.
    Source code(tar.gz)
    Source code(zip)
  • v1.1.2(Jul 3, 2013)

  • v1.1.1(Jul 3, 2013)

  • v1.1.0(Jul 3, 2013)

    • Marked Knp\Menu\ItemInterface::getCurrentItem as deprecated
    • Added a recursive filter iterator keeping only displayed items
    • Added a filter iterator keeping only current items
    • Added a recursive iterator for the item
    • Fixed building an array of breadcrumbs when a label has only digits
    • Added a way to mark a label as safe
    • Refactored the ListRenderer to be consistent with the TwigRenderer and provide the same extension points
    • Added a way to attach extra data to an item
    • Removed unnecessary optimization in the TwigRenderer
    • Added some whitespace control in the Twig template to ensure an empty rendering is really empty
    • [BC break] Use the childrenAttributes for the root instead of the attributes
    • Made the default options configurable for the TwigRenderer
    • Added the support for menu registered as factory in PimpleProvider
    • Added a way to use the options in knp_menu_get() in Twig templates
    • Added an array of options for the MenuProviderInterface
    • Added a template to render an ordered list
    • Refactored the template a bit to make it easier to use an ordered list
    • Allow omitting the name of the child in fromArray (the key is used instead)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jul 3, 2013)

    • Add composer.json file
    • Added more flexible list element blocks
    • Add support for attributes on the children collection.
    • Added a default renderer
    • Added a ChainProvider for the menus.
    • Added the Silex extension
    • Added a RouterAwareFactory
    • Added an helper to be able to reuse the logic more easily for other templating engines
    • Added a way to retrieve an item using a path in a menu tree
    • Changed the toArray method to use a depth instead of simply using a boolean flag
    • Refactored the export to array and the creation from an array
    • Added better support for encoding problems when escaping a string in the ListRenderer
    • Added a Twig renderer
    • Added missing escaping in the ListRenderer
    • Renamed some methods in the ItemInterface
    • Removed the configuration of the current item as link from the item
    • Refactored the ListRenderer to use options
    • Changed the interface of callRecursively
    • Refactored the NodeInterface to be consistent
    • Moved the creation of the item to the factory
    • Added a Twig extension to render the menu easily
    • Changed the menu provider interface with a pimple-based implementation
    • Added a renderer provider to get a renderer by name and a Pimple-based implementation
    • Removed the renderer from the menu
    • Removed the num in the item by refactoring isLast and isFirst
    • Changed the RendererInterface to accept an array of options to be more flexible
    • Added an ItemInterface
    • Initial import of KnpMenuBundle decoupled classes with a new namespace
    Source code(tar.gz)
    Source code(zip)
KNP Labs
Happy Awesome Developers
KNP Labs
Html menu generator for Laravel

Html Menu Generator for Laravel This is the Laravel version of our menu package adds some extras like convenience methods for generating URLs and macr

Spatie 813 Jan 4, 2023
A TWBS menu builder for Laravel

Laravel Menu Builder A menu builder for Laravel 4-5 using Bootstrap's markup. Документация на Русском Note that this package is shipped with no styles

Alexander Kalnoy 24 Nov 29, 2022
📝 Artisan Menu - Use Artisan via an elegant console GUI

?? Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

Jordan Hall 149 Dec 29, 2022
MUP - Menu Up

MUP (aka: 'Menu Up') What is it? It's a bash script that generates a selection menu from a simple configuration file. Config: [Cache: Flush && Clean]

Nathan 9 Aug 19, 2020
📝 Artisan Menu - Use Artisan via an elegant console GUI

?? Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

Jordan Hall 148 Nov 29, 2022
This tool gives you the ability to set the default collapse state for Nova 4.0 menu items.

Nova Menu Collapsed This tool gives you the ability to set the default collapse state for Nova 4.0 menu items. Requirements php: >=8.0 laravel/nova: ^

Artem Stepanenko 10 Nov 17, 2022
Plugin for Filament Admin that adds a dropdown menu to the header to quickly create new items.

Filament Quick Create Plugin for Filament Admin that adds a dropdown menu to the header to quickly create new items from any page. Installation Instal

Adam Weston 45 Dec 27, 2022
Lavacharts is a graphing / charting library for PHP 5.4+ that wraps Google's Javascript Chart API.

Lavacharts 3.1.12 Lavacharts is a graphing / chart library for PHP5.4+ that wraps the Google Chart API. Stable: Dev: Developer Note Please don't be di

Kevin Hill 616 Dec 17, 2022
A laravel service provider for the netsuite-php library service

netsuite-laravel A PHP supplemental package to the ryanwinchester/netsuite-php package to add the NetSuite service client to the service container of

NetsuitePHP 6 Nov 9, 2022
PHP client library for reCAPTCHA, a free service to protect your website from spam and abuse.

reCAPTCHA PHP client library reCAPTCHA is a free CAPTCHA service that protects websites from spam and abuse. This is a PHP library that wraps up the s

Google 3.3k Dec 23, 2022
PHP 5.3 Object Oriented image manipulation library

Imagine Tweet about it using the #php_imagine hashtag. Image manipulation library for PHP 5.3 inspired by Python's PIL and other image libraries. Requ

null 4.3k Dec 29, 2022
Flexihash is a small PHP library which implements consistent hashing.

Flexihash Flexihash is a small PHP library which implements consistent hashing, which is most useful in distributed caching. It requires PHP5 and uses

Paul Annesley 364 Oct 18, 2022
Geo-related tools PHP 7.3+ library built atop Geocoder and React libraries

Geotools Geotools is a PHP geo-related library, built atop Geocoder and React libraries. Features Batch geocode & reverse geocoding request(s) in seri

The League of Extraordinary Packages 1.3k Dec 27, 2022
A PHP library for simplifying the use of accessors.

Accessor A PHP library for simplifying the use of accessors. Usage use Doctrine\ORM\Mapping as ORM; use Phine\Accessor\AccessorTrait; use Phine\Access

KHerGe - Archived Projects 5 May 14, 2020
A small PHP library for validating VAT identification numbers (VATINs).

VATIN A small PHP library for validating VAT identification numbers (VATINs). Installation This library is available on Packagist: $ composer require

David de Boer 128 Oct 27, 2022
Laravel Package for TMDB ( The Movie Database ) API. Provides easy access to the wtfzdotnet/php-tmdb-api library.

Laravel Package for TMDB API Wrapper A Laravel package that provides easy access to the php-tmdb/api TMDB (The Movie Database) API wrapper. This packa

PHP - The Movie Database 151 Nov 1, 2022
Library to intercept PHP includes

Library to intercept and dynamically transform PHP includes. Forked from icewind1991/interceptor.

Nikita Popov 68 Sep 15, 2022
Laravel breeze is a PHP Laravel library that provides Authentication features such as Login page , Register, Reset Password and creating all Sessions Required.

About Laravel breeze To give you a head start building your new Laravel application, we are happy to offer authentication and application starter kits

null 3 Jul 30, 2022
PHP library for sending messages using a ntfy server.

ntfy-php-library PHP library for sending messages using a ntfy server. Supports ntfy server version 1.27.2. Install composer require verifiedjoseph/nt

Joseph 6 Dec 14, 2022