Symfony2 的活动包

Active Bundles of Symfony2

我正在尝试显示我的捆绑包的菜单,但我只需要显示活动的捆绑包,我怎样才能在 Twig 中获得活动的捆绑包?

感谢和问候!

bundle列表存储在内核中。

您必须创建一个 twig 扩展 BundleExtension 并将内核作为依赖项传递:

<?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';
    }
}

将其注册为服务:

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

现在在你的树枝模板中:

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