Check in a Twig template if the current route belongs from a specific Symfony2 bundle

bundle, routes, symfony, twig

Solution

Looking at the Request object, I found a possible solution.

The controller is attached to the `Request` object, hence one can extract it in Twig from the string:

app.request.attributes.get('_controller')

and so retrieve the bundle name. For instance one can define through a TwigExtension such a filter function, e.g.

public function getFilters() {
    return array(
        ...//other filters
        'bundleName'=>new \Twig_Filter_Method($this, 'bundleNameFilter'),
    );
}

public static function bundleNameFilter($string){
  return strstr(substr(strstr($string, '\\'), 1), '\\', true);
} 

Then, in twig use it as follows:

{{  app.request.attributes.get('_controller') | bundleName }}

Hope it helps.

Problem

A Symfony2 app is usually organized around bundles. Each bundle contains (many) controllers. Each controller should be mapped with a route. Practically speaking, routes are usually stored in a specific file under the `config` folder of the bundle or, eventually, annotated inside each controller. What I'm looking for is a way in Twig to identify if the current route belongs from a specific Symfony bundle. Is it possible? Please, as a final remark, consider that the route name should follows the namespace of the controller, in my opinion, but it could also be a random but unique name, e.g. `qwer_XX` instead of `ACME_HomeBundle_home`. Hence, we cannot resort to a namespace-to-route-name association to do what I'm asking for.

Original source