Check the Twig pattern if the current route belongs to a specific set of Symfony2

Symfony2 is usually organized around packages. Each kit contains (many) controllers. Each controller must be mapped to a route.

Practically speaking, routes are usually stored in a specific file in the configpackage folder or, in the end, annotated inside each controller.

What I'm looking for is a way in Twig to determine if the current route belongs to a specific Symfony package. Is it possible?

Please, as a last note, think that the route name should, in my opinion, follow the namespace of the controller, but it can also be a random but unique name, for example. qwer_XXinstead of ACME_HomeBundle_home. Therefore, we cannot resort to the namespace-to-route-name association to do what I ask.

+5
source share
1 answer

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

The controller is attached to the object Request, so it can be retrieved in Twig from the line:

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

and so get the package name. For example, you can define such a filter function through TwigExtension , for example

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 the branch use it like this:

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

Hope this helps.

+6

All Articles