10

How can I detect in which bundle am I?

for exemple, when I'm in web.com/participants/list, I want to read "participants".

j0k
  • 22,600
  • 28
  • 79
  • 90
Bernat
  • 1,537
  • 3
  • 18
  • 40

4 Answers4

15

In order to get the bundle name in the controller:

// Display "AcmeHelloBundle"
echo $this->getRequest()->attributes->get('_template')->get('bundle');

And inside a Twig template:

{{ app.request.get('_template').get('bundle') }}

In order to get the controller name in the controller:

// Display "Default"
echo $this->getRequest()->attributes->get('_template')->get('controller');

And inside a Twig template:

{{ app.request.get('_template').get('controller') }}

In order to get the action name in the controller:

// Displays "index"
echo $this->getRequest()->attributes->get('_template')->get('name');

And inside a Twig template:

{{ app.request.get('_template').get('name') }}
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 6
    pretty sure `->attributes->get('_template')` isn't available if you don't use the @template annotation. – Leevi Graham Apr 18 '14 at 02:30
  • you may use `$request->attributes->get('_controller');` or `$this->getRequest()->attributes->get('_controller');` in controller to grab controller name. – Shadman Apr 29 '14 at 10:47
7

AFAIK it's not yet possible (at least in a easy way). You should use reflection. I wrote a quick and dirty service to do get bundle name ang guess entity/repository/form names based on my conventions. Can be buggy, take a look at: http://pastebin.com/BzeXAduH

It works only when you pass a class that inherits from Controller (Symfony2). Usage:

entity_management_guesser:
  class: Acme\HelloBundle\Service\EntityManagementGuesser

In your controller:

$guesser = $this->get('entity_management_guesser')->inizialize($this);

$bundleName  = $guesser->getBundleName();      // Acme/HelloBundle
$bundleShort = $guesser->getBundleShortName(); // AcmeHelloBundle

Another possibility would be using kernel to get all bundles: Get a bundle name from an entity

Community
  • 1
  • 1
gremo
  • 47,186
  • 75
  • 257
  • 421
  • It's been 2.5 years since the response, anyone heard of any advancements yet on the question? :) Is there a "cleaner" way to find the bundle name? :) – Dimitry K Aug 28 '14 at 09:10
6

Well you can get the controller of the current route by,

$request->attributes->get('_controller');

You can parse the bundle name from it.

Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
3

You can get the bundle name in the controller simply like that:

// Display "SybioCoreBundle"
echo $this->getRequest()->attributes->get('_template')->get('bundle');

And inside a Twig template:

{{ app.request.get('_template').get('bundle') }}
Sybio
  • 8,565
  • 3
  • 44
  • 53