沃梦达 / 编程问答 / php问题 / 正文

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

Symfony2 - get main request#39;s current route in twig partial/subrequest(Symfony2 - 在树枝部分/子请求中获取主请求的当前路由)

本文介绍了Symfony2 - 在树枝部分/子请求中获取主请求的当前路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单独控制器渲染的 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...

这篇关于Symfony2 - 在树枝部分/子请求中获取主请求的当前路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Symfony2 - 在树枝部分/子请求中获取主请求的当前路由

基础教程推荐