I want to choose current url and add active
class for menu item.
How I can get controller, action and slug from current URL from Symfony Extensions
? Not in the Twig
template but in the extension. For example, my extension is <site_root_directory>/src/Twig/AppExtensions.php
.
AppExtensions.php
:
<?php
namespace App\Twig;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class AppExtensions extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction(
'mainMenuExtension',
[$this, 'getMainMenuWidget'],
[
'is_safe' => ['html'],
'needs_environment' => true,
]
),
];
}
public function getMainMenuWidget(Environment $environment)
{
$menu = [
['path' => 'page_home', 'title' => 'Home', 'active' => true],
['path' => 'page_categories', 'title' => 'Categories'],
['path' => 'page_category', 'title' => 'Politics', 'slug' => 'politics'],
['path' => 'page_category', 'title' => 'Business', 'slug' => 'business'],
['path' => 'page_category', 'title' => 'Health', 'slug' => 'health'],
['path' => 'page_category', 'title' => 'Design', 'slug' => 'design'],
['path' => 'page_category', 'title' => 'Sport', 'slug' => 'sport'],
['path' => 'page_about', 'title' => 'About'],
['path' => 'page_contact', 'title' => 'Contact'],
];
return $environment->render('widgets/MainMenu.html.twig', [
'menu' => $menu,
]);
}
}