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

Posted

技术标签:

【中文标题】从扩展中获取当前控制器动作和 slug【英文标题】:Get current controller action and slug from extension 【发布时间】:2021-09-08 16:49:38 【问题描述】:

我想选择当前网址并为菜单项添加active 类。

如何从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,
        ]);
    


【问题讨论】:

这能回答你的问题吗? How to get current route in Symfony 2? 【参考方案1】:

您可以从RequestStack 服务那里获取当前的 url/路由,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,
        ]);
    

【讨论】:

正是我需要的。谢谢!

以上是关于从扩展中获取当前控制器动作和 slug的主要内容,如果未能解决你的问题,请参考以下文章

在 MVC3 中,如何获取当前的动作名称?

在 Controller 中获取当前扩展名

Yii2 - 获取控制器的动作但是使用url

MVC 4 创建 slug 类型 url

ZF2 - 从其他动作和模块渲染视图

MVC如何从视图调用控制器中的动作以返回值