How to get current route in Symfony 2?

2019-01-04 06:26发布

How do I get the current route in Symfony 2?

For example, routing.yml:

somePage:
   pattern: /page/
   defaults: { _controller: "AcmeBundle:Test:index" }

How can I get this somePage value?

12条回答
Rolldiameter
2楼-- · 2019-01-04 06:36

With Twig : {{ app.request.attributes.get('_route') }}

查看更多
在下西门庆
3楼-- · 2019-01-04 06:38

With Symfony 3.3, I have used this method and working fine.

I have 4 routes like

admin_category_index, admin_category_detail, admin_category_create, admin_category_update

And just one line make an active class for all routes.

<li  {% if app.request.get('_route') starts with 'admin_category' %} class="active"{% endif %}>
 <a href="{{ path('admin_category_index') }}">Product Categoires</a>
</li>
查看更多
Luminary・发光体
4楼-- · 2019-01-04 06:43

All I'm getting from that is _internal

I get the route name from inside a controller with $this->getRequest()->get('_route'). Even the code tuxedo25 suggested returns _internal

This code is executed in what was called a 'Component' in Symfony 1.X; Not a page's controller but part of a page which needs some logic.

The equivalent code in Symfony 1.X is: sfContext::getInstance()->getRouting()->getCurrentRouteName();

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-04 06:44
$request->attributes->get('_route');

You can get the route name from the request object from within the controller.

查看更多
够拽才男人
6楼-- · 2019-01-04 06:46

I think this is the easiest way to do this:

class MyController extends Controller
{
    public function myAction($_route)
    {
        var_dump($_route);
    }

    .....
查看更多
混吃等死
7楼-- · 2019-01-04 06:47

From something that is ContainerAware (like a controller):

$request = $this->container->get('request');
$routeName = $request->get('_route');
查看更多
登录 后发表回答