Search code examples
symfonytwigbundles

Active Bundles of Symfony2


I'm trying to show a menu of my Bundles, but I need show only the Bundles that are active, how can I get the active Bundles in Twig?

Thanks and Regards!


Solution

  • The list of bundle is stored in the kernel.

    You have to create a twig extension BundleExtension and pass the kernel as dependency:

    <?php 
    
    namespace MyBundle\Twig\Extension;
    
    use Symfony\Component\HttpKernel\KernelInterface;
    
    class BundleExtension extends \Twig_Extension 
    {
    
        protected $kernel;
    
        public function __construct(KernelInterface $kernel)
        {
            $this->kernel = $kernel;
        }
    
        /**
         * {@inheritdoc}
         * @see Twig_Extension::getFunctions()
         */
        public function getFunctions()
        {
            return array(
                'getBundles' => new \Twig_SimpleFunction('getBundles', array($this, 'getBundles')),
            );
        }
    
         public function getBundles()
         {
            return $this->kernel->getBundles();
         }
    
        /**
         * {@inheritdoc}
         * @see Twig_ExtensionInterface::getName()
         */
        public function getName()
        {
            return 'get_bundles';
        }
    }
    

    Register it as a service:

    services:
        bundle_extension:
            class: MyBundle\Twig\Extension\BundleExtension
            arguments: ['@kernel']
            tags:
               - { name: twig.extension }     
    

    And now in your twig template:

    {% set bundles = getBundles() %}
    {% for bundle in bundles %}
        {{ bundle.getName()}}<br/>
    {% endfor %}