symfony - 获取 Symfony 3.3 和 Twig 中的当前路线

标签 symfony twig

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

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

{{ 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 这样的 URL,我想检索 /article/5。如何执行此操作?

最佳答案

下面的代码片段就可以解决这个问题:

{{ 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 }}

关于symfony - 获取 Symfony 3.3 和 Twig 中的当前路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391808/

相关文章:

Symfony 2 - 加载 Web 调试工具栏时出错 (404 : Not Found)

TWIG 和 "unexpected T_FUNCTION"返回 hostmonster.com 的服务器 500 错误

Symfony2 获取在 twig 中调用的 Action 请求

symfony - 如何访问 Controller 中的防火墙配置?

validation - "required"基于表单中validation_groups的断言

forms - 如何在 Symfony 项目中以嵌入形式从 Twig 访问底层对象

php - Symfony2/Twig - 从动态数组键获取数组

php - Twig nl2br 过滤器不适用于实体

login - Symfony3 - 扩展命名空间

symfony - FOSRestBundle 和 JMSSerializer 运行时公开