Symfony2 - 在树枝部分/子请求中获取主请求的当前路由

2022-01-22 00:00:00 php symfony twig

在单独控制器渲染的 Twig 部分中,我想检查当前主路由是否等于比较路由,因此我可以将列表项标记为活动.

In Twig partial rendered by separate controller, I want to check if current main route equals to compared route, so I can mark list item as active.

我该怎么做?尝试在 BarController 中获取当前路由,例如:

How can I do that? Trying to get current route in BarController like:

$route = $request->get('_route');

返回 null.

Uri 也不是我想要的,就像在 bar's twig 中调用下面的代码:

Uri is also not what I'm looking for, as calling below code in bar's twig:

app.request.uri

返回类似于:localhost/_fragment?path=path_to_bar_route

完整示例

主控制器:FooController 扩展了控制器{

Main Controller: FooController extends Controller{

    public function fooAction(){}
}

fooAction 树枝:

fooAction twig:

...some stuff...

{{ render(controller('FooBundle:Bar:bar')) }}

...some stuff...

条形控制器:

BarController extends Controller{

    public function barAction(){}
}

barAction 树枝:

barAction twig:

<ul>   
    <li class="{{ (item1route == currentroute) ? 'active' : ''}}">
        Item 1
    </li>
    <li class="{{ (item2route == currentroute) ? 'active' : ''}}">
        Item 2
    </li>
    <li class="{{ (item3route == currentroute) ? 'active' : ''}}">
        Item 3
    </li>  
</ul>

推荐答案

pabgaran 的解决方案应该有效.但是,最初的问题可能是由于 request_stack 造成的.

pabgaran's solution should work. However, the original problem occurs probably because of the request_stack.

http://symfony.com/blog/new-in-symfony-2-4-the-request-stack

由于您处于子请求中,因此您应该能够获得顶级(master)Request并获得_route.像这样的:

Since you are in a subrequest, you should be able to get top-level (master) Request and get _route. Something like this:

public function barAction(Request $request) {
    $stack = $this->get('request_stack');
    $masterRequest = $stack->getMasterRequest();
    $currentRoute = $masterRequest->get('_route');

    ...
    return $this->render('Template', array('current_route' => $currentRoute );
}

还没有运行,但它应该可以工作......

Haven't run this but it should work...

相关文章