Registering your own renderer
Registering your own renderer in the renderer provider is simply a matter
of creating a service tagged with knp_menu.renderer
:
1 2 3 4 5 6 7 8 9 10 11
# config/services.yaml
services:
app.menu_renderer:
# The class implements Knp\Menu\Renderer\RendererInterface
class: App\Menu\CustomRenderer
arguments: ["%kernel.charset%"] # set your own dependencies here
tags:
# The alias is what is used to retrieve the menu
- { name: knp_menu.renderer, alias: custom }
# ...
If your renderer extends ListRenderer
, you need to provide a Matcher
instance.
The configuration is then the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# config/services.yaml
services:
app.menu_renderer:
# The class implements Knp\Menu\Renderer\RendererInterface
class: App\Menu\CustomRenderer
arguments:
- '@knp_menu.matcher'
- '%knp_menu.renderer.list.options%'
- '%kernel.charset%'
# add your own dependencies here
tags:
# The alias is what is used to retrieve the menu
- { name: knp_menu.renderer, alias: custom }
# ...
Note
The renderer service must be public as it will be retrieved at runtime to keep it lazy-loaded.
You can now use your renderer to render your menu:
1
{{ knp_menu_render('main', {}, 'custom') }}
Note
As the renderer is responsible to render some HTML code, the knp_menu_render
function is marked as safe. Take care to handle escaping data in your renderer
to avoid XSS if you use some user input in the menu.
This work, including the code samples, is licensed under a
Creative Commons BY-SA 3.0 license.