从扩展中获取当前控制器动作和 slug

Get current controller action and slug from extension

我想选择当前 url 并为菜单项添加 active class。

如何从 Symfony Extensions 的当前 URL 获取控制器、动作和 slug?不在 Twig 模板中,而是在扩展中。比如我的分机是<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,
        ]);
    }

}

您可以从 RequestStack 服务获取当前 url/route getCurrentRequest 此处提供的功能。

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