How to get at runtime the route name in Symfony2 when using the yaml routes description?

笑着哭i 提交于 2019-12-04 11:09:16

问题


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:


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.



来源:https://stackoverflow.com/questions/10349188/how-to-get-at-runtime-the-route-name-in-symfony2-when-using-the-yaml-routes-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!