1

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!

4

1 回答 1

1

捆绑列表存储在内核中。

您必须创建一个树枝扩展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 %}
于 2015-05-20T15:01:11.630 回答