How to get at runtime the route name in Symfony2 w

2019-03-19 19:26发布

Here you can find my n-th question on Symfony2.

I'm working with a pagination bundle that uses the route name provided in the routing.yml file. From my perspective, this approach is not flexible and lead to a dirty code, since if I change the name of the route, then I have to look at all the Twig templates or PHP files to update the route name. This is ok for small Web applications, but will provide such a bug for larger applications and also need an high burden for the developer.

So, I was wondering to pass a string variable x to the Pager object provided by the above mentioned bundle. The string x should be initialized within the controller and has to provide the desired route name as given in the routing.yml file.

Let me give an example. The routing file is the following:

//routing.yml
 AcmeTestBundle_listall:
pattern:  /test/page/{page}
defaults: { _controller: AcmeTestBundle:List:listall, page: 1 }
requirements:
    page:  \d+   

Then the related controller is:

//use something....
class ListController extends Controller
{

  public function exampleAction($page)
  {
    $array = range(1, 100);
    $adapter = new ArrayAdapter($array);
    $pager = new Pager($adapter, array('page' => $page, 'limit' => 25));

    return array('pager' => $pager);  
  }
}

Then, in the twig template, the $pager receives the route name that refer to the above bundle

{% if pager.isPaginable %}
   {{ paginate(pager, 'AcmeTestBundle_listall') }}
{% endif %}
{% for item in pager.getResults %}
   <p>{{ item }}</p>
{% endfor %}

Any idea of how to get the 'AcmeTestBundle_listall' string value at runtime just inside the controller?

1条回答
SAY GOODBYE
2楼-- · 2019-03-19 19:36

You can use the app global variable that is available in twig to get the current route from the request.

{% if pager.isPaginable %}
   {{ paginate(pager, app.request.get('_route') }}
{% endif %}

More about app here and here.

查看更多
登录 后发表回答