0

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,
        ]);
    }

}
LeXxyIT
  • 204
  • 2
  • 15
  • Does this answer your question? [How to get current route in Symfony 2?](https://stackoverflow.com/questions/7096546/how-to-get-current-route-in-symfony-2) – Nico Haase Jun 26 '21 at 16:19

1 Answers1

2

You can get current url/route from RequestStack service there getCurrentRequest function available here.

class AppExtensions extends AbstractExtension
{
    private $requestStack;
    private $environment;
    public function __construct(RequestStack $requestStack, Environment $environment)
    {
        $this->requestStack = $requestStack;
        $this->environment = $environment;
    }

    public function getMainMenuWidget()
    {
        /** @var Request $request */
        $request = $this->requestStack->getCurrentRequest();
        $pathInfo = $request->getPathInfo();
        
        // get current route
        $route = $pathInfo['_route'];

        $menu = [];

        return $this->environment->render('widgets/MainMenu.html.twig', [
            'menu' => $menu,
        ]);
    }
}