【问题标题】:Get current route in Symfony 3.3 and Twig在 Symfony 3.3 和 Twig 中获取当前路线
【发布时间】:2018-03-05 15:10:29
【问题描述】:

我想在 Twig 视图中显示 Symfony 3 中的当前路线。

我已经做了一些研究,但没有找到任何解决方案。我在 Twig 视图中尝试以下操作:

{{ app.request.uri }}

它返回类似:http://localhost:8000/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3DFOSUserBundle%253ASecurity%253Alogin

{{ app.request.get('_route') }}

总是返回 NULL。

{{ app.request.getpathinfo }}

总是有:/_fragment

我需要的很简单。对于localhost:8000/article/5 之类的网址,我想检索/article/5。该怎么做?

【问题讨论】:

    标签: symfony twig


    【解决方案1】:

    下面的代码 sn-p 可以解决问题:

    {{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) }}
    

    app.request.attributes.get('_route') - 返回当前路由名称。

    app.request.attributes.get('_route_params') - 返回当前路由参数。

    path() - 通过路由名称和参数生成路由路径。

    这种方法不适用于转发的请求。在转发请求的情况下,有一个workaround:您应该将“_route”和“_route_params”传递给转发的参数列表。

    return $this->forward('Yourbundle:Controller:action', array(
        //... your parameters...,
        '_route' => $this->getRequest()->attributes->get('_route'),
        '_route_params' => $this->getRequest()->attributes->get('_route_params');
    ));
    

    您还可以使用app.request 访问任何Request 对象函数,例如getPathInfo(),它应该返回当前路由路径。

    {{ app.request.pathInfo }}
    

    【讨论】:

    • 谢谢,但我读到几个消息来源说app.request.get('_route') 仅用于调试目的,而且速度可能很慢。和app.request.attributes.get('_route')一样吗?这个问题今天仍然存在吗?
    • "app.request" 指的是一个 Request 对象,它被设计用于应用程序的任何部分(在任何环境中)来访问请求相关信息,而不是使用 PHP 全局变量。
    • 用转发请求问题的解决方法更新了我的答案。
    猜你喜欢
    • 2016-05-21
    • 1970-01-01
    • 2015-05-08
    • 2015-02-06
    • 2014-02-25
    • 2015-12-04
    • 2014-09-10
    • 1970-01-01
    相关资源
    最近更新 更多