Skip to content

Instantly share code, notes, and snippets.

@reynadan
Created March 26, 2021 10:43
Show Gist options
  • Save reynadan/16cc55436150140fe989df199485b598 to your computer and use it in GitHub Desktop.
Save reynadan/16cc55436150140fe989df199485b598 to your computer and use it in GitHub Desktop.
Customize html KnpMenuBundle in Symfony 5.X
{% extends 'knp_menu.html.twig' %}
{% block item %}
{%- set is_heading = ('heading' in item.attribute('class', [])) %}
{{ parent() }}
{% endblock %}
{% block spanElement %}
{% if is_heading %}
{{ block('heading') }}
{% else %}
{{ parent() }}
{% endif %}
{% endblock %}
{% block label %}
{% if is_heading %}
{{ block('heading') }}
{% else %}
{# Customize your HTML / CSS Here !#}
{% if item.extras.icon_class is defined %}
<i class="{{ item.extras.icon_class }}"></i>
{% endif %}
{% apply spaceless %}
{{ item.label|trans }}
{% endapply %}
{% endif %}
{% endblock %}
{% block heading %}
<h3 class="uppercase font-red-thunderbird">
{{ item.label|trans }}
</h3>
{% endblock %}
<!-- BEGIN SIDEBAR MENU -->
{{ knp_menu_render('main') }}
<!-- END SIDEBAR MENU -->
# KnpMenuBundle Configuration
knp_menu:
twig:
template: '_menu.html.twig'
<?php
namespace App\Core\Menu;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
class MenuBuilder
{
private $factory;
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
public function createMainMenu(): ItemInterface
{
$menu = $this->factory
->createItem('root')
->setChildrenAttributes([
'class' => 'menu-nav',
]);
$menu->addChild('Home', [
'route' => 'homepage',
'extras' => [
'icon_class' => 'fa fa-home',
],
'attributes' => ['class' => 'menu-item menu-item-submenu'],
])->setLinkAttribute('class', 'menu-link');
return $menu;
}
}
services:
app.menu.builder:
class: App\Menu\MenuBuilder
arguments:
- '@knp_menu.factory'
- '@security.authorization_checker'
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main }
twig:
paths:
- '%kernel.project_dir%/templates'
- '%kernel.project_dir%/vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment