Symfony2 - 在 TWIG 模板中获取当前 URL 或路由?

Symfony2 - Get the current URL or route in TWIG template?

我的路线是

admin:
      path:     /admin/
      defaults: { _controller: CatalogWebBundle:Admin:admin }

如何在 PHP 模板中获取路线名称?

获取当前URL

$request->getRequestUri();app.request.uri

至于路由本身,最佳做法是将其作为参数注入到控制器中,请参阅 the doc here. You could use $request->attributes->get('_route') or app.request.attributes.get('_route') but it is not as reliable, for example it won't work with forwards as you are forwarding to a controller, not to a path. And it is really only meant for debugging purposes according to Fabien (@fabpot), the creator,因此为了将来的升级我不会依赖它。

旁注

记得随时avoid $request->get(),所以不要 $request->get('_route') 正如我在类似问题的一些答案中看到的那样

If you don't need the flexibility in controllers, it is better to explicitly get request parameters from the appropriate public property instead (attributes, query, request)

原因是它会查看所说的 public 属性(属性、查询和请求),而不仅仅是一个(属性),这使得它变得更慢

要在 Symfony2 中获取路由名称,请输入以下代码片段

$request = $this->container->get('request');
$routeName = $request->get('_route');

要在 Symfony2 中获得 URL,

$request = $this->container->get('request');
$routeURL = $request->getRequestUri();

直接在 Twig 中做不是一件好事,但你仍然可以做。更好的方法是将其作为控制器的参数传递。

获取Twig中的路由参数。

{{ app.request.attributes.get('_route_params') }}

在 Twig 中获取整个包名称。

{{ app.request.attributes.get("_controller") }}

在 Twig 中获取路由名称。

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

补充说,在某些情况下,app.request.uri 不会 return 当前页面的 url。

示例:在您的页面模板中,您通过以下方式调用控制器:

{{ render(controller('AppBundle:MyController:myBlock')) }}

然后在 myBlockAction 中渲染另一个模板,比如 block.html.twig

block.html.twig 调用 app.request.uri 将显示如下内容:

http://www.example.com/app.php/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3DAppBundle%253AMyController%253AmyBlock

如果你想从 block.html.twig 中获取渲染页面的绝对值 url,你可以从 php $_SERVER 变量重新组装它:

{{ app.request.server.get('REQUEST_SCHEME') ~ '://' ~ 
   app.request.server.get('SERVER_NAME') ~ 
   app.request.server.get('PHP_SELF') }}

如果需要,您还可以添加 QUERY_STRING

在 symfony5 上你可以这样做。

调用控制器块并传递电流url:

{{ render_esi(controller('App\Controller\Frontend\BlockController::social',{'pageUri': app.request.uri })) }}

<?php

namespace App\Controller\Frontend;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class BlockController extends AbstractController {
    public function social($pageUri) {
        return $this->render('block/_social.html.twig', ['pageUri' => $pageUri]);
    }

}

输出树枝: 'block/_social.html.twig'

<small>Current Url : {{ pageUri  }}</small>