JeanValjean JeanValjean - 18 days ago 5x
Twig Question

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

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

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

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

pattern: /test/page/{page}
defaults: { _controller: AcmeTestBundle:List:listall, page: 1 }
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
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?


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.